Skip to content

Commit

Permalink
Code refactoring and drying
Browse files Browse the repository at this point in the history
  • Loading branch information
wAsnk committed Oct 30, 2024
1 parent 593d5f7 commit abfca0f
Show file tree
Hide file tree
Showing 15 changed files with 191 additions and 227 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,6 @@ namespace OrchardCore.Commerce.Payment.Stripe.Abstractions;
/// </summary>
public interface IStripePaymentService
{
Task<SubscriptionCreateResponse> CreateSubscriptionAsync(StripeCreateSubscriptionViewModel viewModel);

Task<Customer> GetCustomerAsync(string customerId);

Task<Customer> CreateCustomerAsync(CustomerCreateOptions customerCreateOptions);

Task<ConfirmationToken> GetConfirmationTokenAsync(string confirmationTokenId);

long GetPaymentAmount(Amount total);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,7 @@
using OrchardCore.Commerce.Payment.Stripe.Endpoints.Models;
using OrchardCore.Commerce.Payment.Stripe.Endpoints.Permissions;
using OrchardCore.Commerce.Payment.Stripe.Services;
using OrchardCore.Environment.Shell;
using Stripe.Checkout;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

using static OrchardCore.Commerce.Payment.Stripe.Endpoints.Constants.Endpoints;
Expand All @@ -30,16 +27,14 @@ private static async Task<IResult> GetStripeCheckoutEndpointAsync(
[FromServices] IAuthorizationService authorizationService,
[FromServices] IStripeCustomerService stripeCustomerService,
[FromServices] IStripeSessionService stripeSessionService,
[FromServices] ShellSettings shellSettings,
HttpContext httpContext)
{
if (!await authorizationService.AuthorizeAsync(httpContext.User, ApiPermissions.CommerceApiStripePayment))
{
return httpContext.ChallengeOrForbidApi();
}

//TODO: We need update also
var customer = await stripeCustomerService.GetOrCreateCustomerAsync(
var customer = await stripeCustomerService.GetAndUpdateOrCreateCustomerAsync(
viewModel.BillingAddress,
viewModel.ShippingAddress,
viewModel.Email,
Expand All @@ -53,30 +48,10 @@ private static async Task<IResult> GetStripeCheckoutEndpointAsync(
SuccessUrl = viewModel.SuccessUrl,
CancelUrl = viewModel.CancelUrl,
Customer = customer.Id,
SubscriptionData = new SessionSubscriptionDataOptions
{
Metadata = new Dictionary<string, string>
{
{ "tenantName", shellSettings.Name },
},
},
};

foreach (var lineItem in options.LineItems)
{
//TODO: Change this to use the actual tax rate
lineItem.TaxRates = ["txr_1F3586L1SJaDnrcsvfTTvknD"];
}

var session = await stripeSessionService.CreateSessionAsync(options);

//Save session id to DB, with current User data and other necessary data
var result = await stripeSessionService.SaveSessionDataAsync(customer, session);
if (result.Errors?.Any() == true)
{
return TypedResults.BadRequest(result.Errors);
}

return TypedResults.Ok(session.Url);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@ public class SubscriptionCheckoutEndpointViewModel
{
public string SuccessUrl { get; set; }
public string CancelUrl { get; set; }

// This is an API model so we don't need to make it read-only.
#pragma warning disable CA2227 // CA2227: Change 'SessionLineItemOptions' to be read-only by removing the property setter
public IList<SessionLineItemOptions> SessionLineItemOptions { get; set; } = new List<SessionLineItemOptions>();
#pragma warning restore CA2227
public PaymentMode PaymentMode { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using OrchardCore.Commerce.Payment.Stripe.Abstractions;
using OrchardCore.Commerce.Payment.Stripe.Endpoints.Permissions;
using OrchardCore.Commerce.Payment.Stripe.Services;
using Stripe;
using System.Threading.Tasks;
using static OrchardCore.Commerce.Payment.Stripe.Endpoints.Constants.Endpoints;
Expand All @@ -22,7 +22,7 @@ public static IEndpointRouteBuilder AddStripeGetCustomerEndpoint(this IEndpointR

private static async Task<IResult> GetStripeCustomerAsync(
[FromQuery] string? customerId,
[FromServices] IStripePaymentService stripePaymentService,
[FromServices] IStripeCustomerService stripeCustomerService,
[FromServices] IAuthorizationService authorizationService,
HttpContext httpContext)
{
Expand All @@ -31,7 +31,7 @@ private static async Task<IResult> GetStripeCustomerAsync(
return httpContext.ChallengeOrForbidApi();
}

var customer = await stripePaymentService.GetCustomerAsync(customerId);
var customer = await stripeCustomerService.GetCustomerByIdAsync(customerId);
return TypedResults.Ok(customer);
}

Expand All @@ -43,7 +43,7 @@ public static IEndpointRouteBuilder AddStripeCreateCustomerEndpoint(this IEndpoi

private static async Task<IResult> GetStripeCreateCustomerAsync(
[FromBody] CustomerCreateOptions customerCreateOptions,
[FromServices] IStripePaymentService stripePaymentService,
[FromServices] IStripeCustomerService stripeCustomerService,
[FromServices] IAuthorizationService authorizationService,
HttpContext httpContext)
{
Expand All @@ -52,7 +52,7 @@ private static async Task<IResult> GetStripeCreateCustomerAsync(
return httpContext.ChallengeOrForbidApi();
}

var customer = await stripePaymentService.CreateCustomerAsync(customerCreateOptions);
var customer = await stripeCustomerService.CreateCustomerFromOptionsAsync(customerCreateOptions);
return TypedResults.Ok(customer);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using OrchardCore.Commerce.Endpoints;
using OrchardCore.Commerce.Payment.Stripe.Abstractions;
using OrchardCore.Commerce.Payment.Stripe.Endpoints.Permissions;
using OrchardCore.Commerce.Payment.Stripe.Extensions;
using OrchardCore.Commerce.Payment.Stripe.Services;
using OrchardCore.Commerce.Payment.Stripe.ViewModels;
using Stripe;
using System.Collections.Generic;
Expand All @@ -27,7 +27,8 @@ public static IEndpointRouteBuilder AddStripeCreateSubscriptionEndpoint(this IEn

private static async Task<IResult> GetStripeCreateSubscriptionAsync(
[FromBody] StripeCreateSubscriptionViewModel viewModel,
[FromServices] IStripePaymentService stripePaymentService,
[FromServices] IStripeCustomerService stripeCustomerService,
[FromServices] IStripeSubscriptionService stripeSubscriptionService,
[FromServices] IShoppingCartService shoppingCartService,
[FromServices] IAuthorizationService authorizationService,
HttpContext httpContext)
Expand Down Expand Up @@ -77,12 +78,12 @@ private static async Task<IResult> GetStripeCreateSubscriptionAsync(
State = billingAddress.Province,
},
};
var customer = await stripePaymentService.CreateCustomerAsync(options);
var customer = await stripeCustomerService.CreateCustomerAsync(options);
viewModel.CustomerId = customer.Id;
}

// Create the subscription.
var subscription = await stripePaymentService.CreateSubscriptionAsync(viewModel);
return TypedResults.Ok(subscription);
var response = await stripeSubscriptionService.CreateSubscriptionAsync(viewModel);
return TypedResults.Ok(response);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,23 @@ namespace OrchardCore.Commerce.Payment.Stripe.Services;

public interface IStripeCustomerService
{
Task<Customer> CreateCustomerAsync(CustomerCreateOptions customerCreateOptions);
Task<Customer> GetFirstCustomerByEmailAsync(string customerEmail);
Task<Customer> GetCustomerByIdAsync(string customerId);
Task<Customer> GetOrCreateCustomerAsync(
Task<Customer> GetAndUpdateOrCreateCustomerAsync(
Address billingAddress,
Address shippingAddress,
string email,
string phone);

Task<Customer> CreateCustomerAsync(
Address billingAddress,
Address shippingAddress,
string email,
string phone);

Task<Customer> UpdateCustomerAsync(
string customerId,
Address billingAddress,
Address shippingAddress,
string email,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
using OrchardCore.Commerce.Payment.Stripe.Models;
using Stripe;
using Stripe.Checkout;
using Stripe.Checkout;
using System.Threading.Tasks;

namespace OrchardCore.Commerce.Payment.Stripe.Services;

public interface IStripeSessionEventHandler
{
Task StripeSessionDataCreatingAsync(StripeSessionData sessionData, Session session, Customer customer);
Task StripeSessionCreatingAsync(SessionCreateOptions options) => Task.CompletedTask;
Task StripeSessionCreatedAsync(Session session, SessionCreateOptions options) => Task.CompletedTask;
}
Original file line number Diff line number Diff line change
@@ -1,18 +1,9 @@
using OrchardCore.Commerce.Payment.Stripe.Models;
using Stripe;
using Stripe.Checkout;
using System.Collections.Generic;
using Stripe.Checkout;
using System.Threading.Tasks;

namespace OrchardCore.Commerce.Payment.Stripe.Services;

public interface IStripeSessionService
{
Task<Session> CreateSessionAsync(SessionCreateOptions options);

Task<StripeSessionDataSave> SaveSessionDataAsync(Customer customer, Session session);

Task<IEnumerable<StripeSessionData>> GetAllSessionDataAsync(string userId, string invoiceId, string sessionId);

Task<StripeSessionData> GetFirstSessionDataByInvoiceIdAsync(string invoiceId);
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using Stripe;
using OrchardCore.Commerce.Payment.Stripe.Models;
using OrchardCore.Commerce.Payment.Stripe.ViewModels;
using Stripe;
using System.Threading.Tasks;

namespace OrchardCore.Commerce.Payment.Stripe.Services;
Expand All @@ -7,4 +9,6 @@ public interface IStripeSubscriptionService
{
Task UpdateSubscriptionAsync(string subscriptionId, SubscriptionUpdateOptions options);
Task<Subscription> GetSubscriptionAsync(string subscriptionId, SubscriptionGetOptions options);
Task<Subscription> CreateSubscriptionAsync(SubscriptionCreateOptions options);
Task<SubscriptionCreateResponse> CreateSubscriptionAsync(StripeCreateSubscriptionViewModel viewModel);
}
Original file line number Diff line number Diff line change
Expand Up @@ -57,12 +57,11 @@ public async Task<Customer> GetFirstCustomerByEmailAsync(string customerEmail)
}
catch (StripeException stripeException)
{

return null;
}
}

public async Task<Customer> GetOrCreateCustomerAsync(
public async Task<Customer> GetAndUpdateOrCreateCustomerAsync(
Address billingAddress,
Address shippingAddress,
string email,
Expand All @@ -77,44 +76,20 @@ public async Task<Customer> GetOrCreateCustomerAsync(

if (customer?.Id != null)
{
customer = await UpdateCustomerAsync(customer.Id, billingAddress, shippingAddress, email, phone);
return customer;
}

return await CreateCustomerAsync(billingAddress, shippingAddress, email, phone);
}

private async Task<Customer> CreateCustomerAsync(Address billingAddress, Address shippingAddress, string email, string phone)
public async Task<Customer> CreateCustomerAsync(
Address billingAddress,
Address shippingAddress,
string email,
string phone)
{
var customerCreateOptions = new CustomerCreateOptions
{
Name = billingAddress.Name,
Email = email,
Phone = phone,
Address = new AddressOptions
{
City = billingAddress.City,
Country = billingAddress.Region,
Line1 = billingAddress.StreetAddress1,
Line2 = billingAddress.StreetAddress2,
PostalCode = billingAddress.PostalCode,
State = billingAddress.Province,
},
Shipping = shippingAddress?.Name != null
? new ShippingOptions
{
Name = shippingAddress.Name,
Address = new AddressOptions
{
City = shippingAddress.City,
Country = shippingAddress.Region,
Line1 = shippingAddress.StreetAddress1,
Line2 = shippingAddress.StreetAddress2,
PostalCode = shippingAddress.PostalCode,
State = shippingAddress.Province,
},
}
: null,
};
var customerCreateOptions = PopulateCustomerCreateOptions(billingAddress, shippingAddress, email, phone);

var customer = await _customerService.CreateAsync(
customerCreateOptions,
Expand All @@ -123,4 +98,79 @@ await _requestOptionsService.SetIdempotencyKeyAsync(),

return customer;
}

public async Task<Customer> CreateCustomerAsync(CustomerCreateOptions customerCreateOptions)
{
var customer = await _customerService.CreateAsync(
customerCreateOptions,
await _requestOptionsService.SetIdempotencyKeyAsync(),
cancellationToken: _hca.HttpContext.RequestAborted);

return customer;
}

public async Task<Customer> UpdateCustomerAsync(
string customerId,
Address billingAddress,
Address shippingAddress,
string email,
string phone)
{
var customerUpdateOptions = PopulateCustomerUpdateOptions(billingAddress, shippingAddress, email, phone);

var customer = await _customerService.UpdateAsync(
customerId,
customerUpdateOptions,
await _requestOptionsService.SetIdempotencyKeyAsync(),
cancellationToken: _hca.HttpContext.RequestAborted);

return customer;
}

private static CustomerUpdateOptions PopulateCustomerUpdateOptions(
Address billingAddress,
Address shippingAddress,
string email,
string phone) =>
new()
{
Name = billingAddress.Name,
Email = email,
Phone = phone,
Address = CreateAddressOptions(billingAddress),
Shipping = CreateShippingOptions(shippingAddress),
};

private static CustomerCreateOptions PopulateCustomerCreateOptions(
Address billingAddress,
Address shippingAddress,
string email,
string phone) =>
new()
{
Name = billingAddress.Name,
Email = email,
Phone = phone,
Address = CreateAddressOptions(billingAddress),
Shipping = CreateShippingOptions(shippingAddress),
};

private static AddressOptions CreateAddressOptions(Address address) => new()
{
City = address.City,
Country = address.Region,
Line1 = address.StreetAddress1,
Line2 = address.StreetAddress2,
PostalCode = address.PostalCode,
State = address.Province,
};

private static ShippingOptions CreateShippingOptions(Address shippingAddress) =>
shippingAddress?.Name != null
? new ShippingOptions
{
Name = shippingAddress.Name,
Address = CreateAddressOptions(shippingAddress),
}
: null;
}
Loading

0 comments on commit abfca0f

Please sign in to comment.