Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dibs - headless solution callback fix + better logging #18

Merged
merged 2 commits into from
Oct 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 31 additions & 6 deletions src/DibsEasyCheckout.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
using Dynamicweb.Rendering;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;

namespace Dynamicweb.Ecommerce.CheckoutHandlers.DibsEasyCheckout
Expand Down Expand Up @@ -219,7 +221,30 @@
order.TransactionStatus = "Failed";
throw new Exception("Dibs payment failed.");
}

var paymentId = Context.Current.Request["paymentId"];

try
{
using var reader = new StreamReader(Context.Current.Request.InputStream, Encoding.UTF8);
string inputStreamRawData = reader.ReadToEndAsync().ConfigureAwait(false).GetAwaiter().GetResult();
if (!string.IsNullOrWhiteSpace(inputStreamRawData))
{
LogEvent(order, $"Read the input stream data: {inputStreamRawData}");

PaymentCheckoutCompleted checkoutCompleted = Converter.Deserialize<PaymentCheckoutCompleted>(inputStreamRawData);
if (checkoutCompleted?.Data?.PaymentId is string pId)
paymentId = pId;
}
}
catch (Exception ex)
{
LogError(order, $"Error during processing input stream to get the webhook data: {ex.Message}");
}

if (string.IsNullOrEmpty(paymentId))
throw new Exception("Payment id is empty.");

UpdateOrderInfo(paymentId, order);

return PassToCart(order);
Expand All @@ -239,7 +264,7 @@
{
LogEvent(order, "Getting payment from Dibs by paymentId");

var service = new DibsService(GetSecretKey(), GetApiUrl());
var service = new DibsService(order, GetSecretKey(), GetApiUrl());
DibsPaymentResponse paymentResponse = service.GetPayment(paymentId);

if (paymentResponse != null)
Expand Down Expand Up @@ -314,7 +339,7 @@

private void ChargePayment(Order order, string paymentId, long chargeAmount)
{
var service = new DibsService(GetSecretKey(), GetApiUrl());
var service = new DibsService(order, GetSecretKey(), GetApiUrl());
CapturePaymentResponse charge = service.CapturePayment(paymentId, chargeAmount);

if (!string.IsNullOrWhiteSpace(charge?.ChargeId))
Expand Down Expand Up @@ -493,7 +518,7 @@
}

long refundAmount = PriceHelper.ConvertToPIP(order.Currency, order.CaptureAmount);
var service = new DibsService(GetSecretKey(), GetApiUrl());
var service = new DibsService(order, GetSecretKey(), GetApiUrl());
RefundPaymentResponse returnResponse = service.RefundPayment(order.TransactionNumber, refundAmount);

LogEvent(order, "Remote return id: {0}", returnResponse.RefundId);
Expand Down Expand Up @@ -534,7 +559,7 @@
return false;
}

var service = new DibsService(GetSecretKey(), GetApiUrl());
var service = new DibsService(order, GetSecretKey(), GetApiUrl());
service.CancelPayment(order.TransactionNumber, order.Price.PricePIP);
LogEvent(order, "Order has been cancelled.");
return true;
Expand Down Expand Up @@ -610,15 +635,15 @@
return string.Empty;
}

private OutputResult RenderPaymentForm(Order order, Template formTemplate, bool headless = false, string? receiptUrl = null)

Check warning on line 638 in src/DibsEasyCheckout.cs

View workflow job for this annotation

GitHub Actions / call-workflow / Build

The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.

Check warning on line 638 in src/DibsEasyCheckout.cs

View workflow job for this annotation

GitHub Actions / call-workflow / Build

The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
{
try
{
string baseUrl = GetBaseUrl(order, headless);
string approvetUrl = GetApprovetUrl(baseUrl);

var service = new DibsService(GetSecretKey(), GetApiUrl());
var newPayment = service.CreatePayment(order, new()
var service = new DibsService(order, GetSecretKey(), GetApiUrl());
var newPayment = service.CreatePayment(new()
{
BaseUrl = baseUrl,
PrefillCustomerAddress = PrefillCustomerAddress,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<VersionPrefix>10.6.2</VersionPrefix>
<VersionPrefix>10.6.3</VersionPrefix>
<AssemblyVersion>1.0.0.0</AssemblyVersion>
<Title>Nets Easy Checkout</Title>
<Description>Nets Easy Checkout</Description>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
namespace Dynamicweb.Ecommerce.CheckoutHandlers.DibsEasyCheckout.Models;

[DataContract]
internal sealed class ErrorResponse
internal sealed class BadRequestResponse
{
[DataMember(Name = "errors")]
public Dictionary<string, IEnumerable<string>> Errors { get; set; }
Expand Down
16 changes: 16 additions & 0 deletions src/Models/InternalServerErrorResponse.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using System.Runtime.Serialization;

namespace Dynamicweb.Ecommerce.CheckoutHandlers.DibsEasyCheckout.Models;

[DataContract]
internal sealed class InternalServerErrorResponse
{
[DataMember(Name = "message")]
public string Message { get; set; }

[DataMember(Name = "Code")]
public string Code { get; set; }

[DataMember(Name = "Source")]
public string Source { get; set; }
}
23 changes: 23 additions & 0 deletions src/Models/Webhooks/PaymentCheckoutCompleted.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using System.Runtime.Serialization;

namespace Dynamicweb.Ecommerce.CheckoutHandlers.DibsEasyCheckout.Models;

//see: https://developer.nexigroup.com/nexi-checkout/en-EU/api/webhooks/#checkout-completed
[DataContract]
internal sealed class PaymentCheckoutCompleted
{
[DataMember(Name = "id")]
public string Id { get; set; }

[DataMember(Name = "merchantId")]
public int MerchantId { get; set; }

[DataMember(Name = "timestamp")]
public string Timestamp { get; set; }

[DataMember(Name = "event")]
public string Event { get; set; }

[DataMember(Name = "data")]
public PaymentCheckoutCompletedData Data { get; set; }
}
10 changes: 10 additions & 0 deletions src/Models/Webhooks/PaymentCheckoutCompletedData.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using System.Runtime.Serialization;

namespace Dynamicweb.Ecommerce.CheckoutHandlers.DibsEasyCheckout.Models;

[DataContract]
internal sealed class PaymentCheckoutCompletedData
{
[DataMember(Name = "paymentId")]
public string PaymentId { get; set; }
}
42 changes: 31 additions & 11 deletions src/Service/DibsRequest.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Dynamicweb.Core;
using Dynamicweb.Ecommerce.CheckoutHandlers.DibsEasyCheckout.Models;
using Dynamicweb.Ecommerce.Orders;
using System;
using System.Collections.Generic;
using System.Linq;
Expand All @@ -16,7 +17,7 @@ namespace Dynamicweb.Ecommerce.CheckoutHandlers.DibsEasyCheckout.Service;
/// </summary>
internal static class DibsRequest
{
public static string SendRequest(string apiUrl, string secretKey, CommandConfiguration configuration)
public static string SendRequest(Order order, string apiUrl, string secretKey, CommandConfiguration configuration)
{
using (var messageHandler = GetMessageHandler())
{
Expand Down Expand Up @@ -46,26 +47,37 @@ ApiCommand.CreatePayment or
{
using (HttpResponseMessage response = requestTask.GetAwaiter().GetResult())
{
string data = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
Log(order, $"Remote server response: HttpStatusCode = {response.StatusCode}, HttpStatusDescription = {response.ReasonPhrase}");
string responseText = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
Log(order, $"Remote server ResponseText: {responseText}");

if (!response.IsSuccessStatusCode)
{
var errorResponse = Converter.Deserialize<ErrorResponse>(data);
if (errorResponse?.Errors?.Any() is true)
if (response.StatusCode is HttpStatusCode.BadRequest)
{
var errorMessage = new StringBuilder();
foreach ((string propertyName, IEnumerable<string> errors) in errorResponse.Errors)
var errorResponse = Converter.Deserialize<BadRequestResponse>(responseText);
if (errorResponse?.Errors?.Any() is true)
{
string errorsText = string.Join(", ", errors);
errorMessage.AppendLine($"{propertyName}: {errorsText}");
var errorMessage = new StringBuilder();
foreach ((string propertyName, IEnumerable<string> errors) in errorResponse.Errors)
{
string errorsText = string.Join(", ", errors);
errorMessage.AppendLine($"{propertyName}: {errorsText}");
}
throw new Exception(errorMessage.ToString());
}
throw new Exception(errorMessage.ToString());
}
else if (response.StatusCode is HttpStatusCode.InternalServerError)
{
var errorResponse = Converter.Deserialize<InternalServerErrorResponse>(responseText);
if (!string.IsNullOrEmpty(errorResponse?.Message))
throw new Exception($"Error code: {errorResponse.Code}. Error source: {errorResponse.Source}. Error message: {errorResponse.Message}");
}

throw new Exception($"Unhandled exception. Operation failed: {response.ReasonPhrase}");
throw new Exception($"Unhandled exception. Operation failed: {response.ReasonPhrase}. Response text: {responseText}");
}

return data;
return responseText;
}
}
catch (HttpRequestException requestException)
Expand Down Expand Up @@ -101,4 +113,12 @@ private static string GetCommandLink(string baseAddress, ApiCommand command, str

string GetCommandLink(string gateway) => $"{baseAddress}/v1/{gateway}";
}

private static void Log(Order order, string message)
{
if (order is null)
return;

Services.OrderDebuggingInfos.Save(order, message, typeof(DibsEasyCheckout).FullName, DebuggingInfoType.Undefined);
}
}
19 changes: 11 additions & 8 deletions src/Service/DibsService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,20 @@ internal sealed class DibsService

public string SecretKey { get; set; }

public DibsService(string secretKey, string apiUrl)
public Order Order { get; set; }

public DibsService(Order order, string secretKey, string apiUrl)
{
Order = order;
SecretKey = secretKey;
ApiUrl = apiUrl;
}

public CreatePaymentResponse CreatePayment(Order order, CreatePaymentParameters parameters)
public CreatePaymentResponse CreatePayment(CreatePaymentParameters parameters)
{
PaymentRequest request = ConvertOrder(order, parameters);
PaymentRequest request = ConvertOrder(Order, parameters);

string response = DibsRequest.SendRequest(ApiUrl, SecretKey, new()
string response = DibsRequest.SendRequest(Order, ApiUrl, SecretKey, new()
{
CommandType = ApiCommand.CreatePayment,
Data = request
Expand All @@ -43,7 +46,7 @@ public CreatePaymentResponse CreatePayment(Order order, CreatePaymentParameters
public DibsPaymentResponse GetPayment(string paymentId)
{

string response = DibsRequest.SendRequest(ApiUrl, SecretKey, new()
string response = DibsRequest.SendRequest(Order, ApiUrl, SecretKey, new()
{
CommandType = ApiCommand.GetPayment,
OperatorId = paymentId
Expand All @@ -54,7 +57,7 @@ public DibsPaymentResponse GetPayment(string paymentId)

public CapturePaymentResponse CapturePayment(string paymentId, long amount)
{
string response = DibsRequest.SendRequest(ApiUrl, SecretKey, new()
string response = DibsRequest.SendRequest(Order, ApiUrl, SecretKey, new()
{
CommandType = ApiCommand.CapturePayment,
OperatorId = paymentId,
Expand All @@ -69,7 +72,7 @@ public CapturePaymentResponse CapturePayment(string paymentId, long amount)

public RefundPaymentResponse RefundPayment(string paymentId, long amount)
{
string response = DibsRequest.SendRequest(ApiUrl, SecretKey, new()
string response = DibsRequest.SendRequest(Order, ApiUrl, SecretKey, new()
{
CommandType = ApiCommand.RefundPayment,
OperatorId = paymentId,
Expand All @@ -84,7 +87,7 @@ public RefundPaymentResponse RefundPayment(string paymentId, long amount)

public void CancelPayment(string paymentId, long amount)
{
string response = DibsRequest.SendRequest(ApiUrl, SecretKey, new()
string response = DibsRequest.SendRequest(Order, ApiUrl, SecretKey, new()
{
CommandType = ApiCommand.CancelPayment,
OperatorId = paymentId,
Expand Down
Loading