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

OCC-52: No Payment Needed Checkout #321

Merged
merged 23 commits into from
Jul 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
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
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using OrchardCore.Commerce.Controllers;
using OrchardCore.Commerce.Controllers;
using OrchardCore.Commerce.Models;
using OrchardCore.Commerce.ViewModels;
using OrchardCore.ContentManagement;
Expand All @@ -23,4 +23,9 @@ Task<CheckoutViewModel> CreateCheckoutViewModelAsync(
/// When the order is payed this logic should be run to set <paramref name="order"/> properties that represents its state.
/// </summary>
Task FinalModificationOfOrderAsync(ContentItem order);

/// <summary>
/// Creates an order content item without payment in the database based on the current <see cref="ShoppingCart"/> content.
/// </summary>
Task<ContentItem> CreateNoPaymentOrderFromShoppingCartAsync();
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using OrchardCore.Commerce.Constants;
using OrchardCore.Commerce.Models;
using OrchardCore.ContentManagement;
using OrchardCore.DisplayManagement.ModelBinding;
Expand Down Expand Up @@ -31,9 +32,10 @@ public interface IStripePaymentService
Task<ContentItem> CreateOrUpdateOrderFromShoppingCartAsync(PaymentIntent paymentIntent, IUpdateModelAccessor updateModelAccessor);

/// <summary>
/// Updates the corresponding order status to Order for the given <paramref name="paymentIntent"/>.
/// Updates the corresponding order status to <see cref="OrderStatuses.Ordered"/> for the given
/// <paramref name="paymentIntent"/> or the provided <paramref name="orderItem"/>.
/// </summary>
Task UpdateOrderToOrderedAsync(PaymentIntent paymentIntent);
Task UpdateOrderToOrderedAsync(PaymentIntent paymentIntent = null, ContentItem orderItem = null);
sarahelsaig marked this conversation as resolved.
Show resolved Hide resolved

/// <summary>
/// Updates the corresponding order status to failed payment for the given <paramref name="paymentIntent"/>.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,6 @@ window.stripePaymentForm = function stripePaymentForm(
.then((response) => response.json());
}


function getText(element) {
return element?.textContent.trim();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
namespace OrchardCore.Commerce.Constants;

public static class OrderStatuses
{
public const string Pending = nameof(Pending);
Expand Down
16 changes: 16 additions & 0 deletions src/Modules/OrchardCore.Commerce/Controllers/PaymentController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,22 @@ public async Task<IActionResult> Success(string orderId)
return View(order);
}

[AllowAnonymous]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CheckoutWithoutPayment()
{
if (await _paymentService.CreateNoPaymentOrderFromShoppingCartAsync() is not { } order)
{
return NotFound();
}

await _stripePaymentService.UpdateOrderToOrderedAsync(orderItem: order);
await _paymentService.FinalModificationOfOrderAsync(order);

return RedirectToAction(nameof(Success), new { orderId = order.ContentItem.ContentItemId });
}

[AllowAnonymous]
[HttpGet("checkout/middleware")]
public async Task<IActionResult> PaymentConfirmationMiddleware([FromQuery(Name = "payment_intent")] string paymentIntent = null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using OrchardCore.DisplayManagement.ModelBinding;
using OrchardCore.DisplayManagement.Views;
using OrchardCore.Workflows.Helpers;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

Expand Down Expand Up @@ -45,8 +46,7 @@ public override async Task<IDisplayResult> UpdateAsync(OrderPart part, IUpdateMo
.Where(lineItem => lineItem.Quantity != 0)
.ToList();

part.LineItems.Clear();
part.LineItems.AddRange(lineItems);
part.LineItems.SetItems(lineItems);

return await EditAsync(part, context);
}
Expand Down
36 changes: 36 additions & 0 deletions src/Modules/OrchardCore.Commerce/Handlers/OrderPartHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using Microsoft.Extensions.Localization;
using OrchardCore.Commerce.Models;
using OrchardCore.ContentManagement;
using OrchardCore.ContentManagement.Handlers;
using System;
using System.Threading.Tasks;
using YesSql;

namespace OrchardCore.Commerce.Handlers;

public class OrderPartHandler : ContentPartHandler<OrderPart>
{
private readonly IStringLocalizer T;
private readonly ISession _session;

public OrderPartHandler(IStringLocalizer<OrderPartHandler> stringLocalizer, ISession session)
{
_session = session;
T = stringLocalizer;
}

public override Task UpdatedAsync(UpdateContentContext context, OrderPart part)
{
if (part.ContentItem.As<OrderPart>() is not { } orderPart) return Task.CompletedTask;

var guid = orderPart.OrderId.Text ?? Guid.NewGuid().ToString();
orderPart.OrderId.Text = guid;

orderPart.ContentItem.DisplayText = T["Order {0}", guid];

orderPart.Apply();
_session.Save(orderPart.ContentItem);

return Task.CompletedTask;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,66 @@
"ProductSku": "TESTPRODUCT"
},
"Product": {}
},
{
"ContentItemId": "testfreeproduct000",
"ContentItemVersionId": "[js:uuid()]",
"ContentType": "Product",
"DisplayText": "TestFreeProduct",
"Latest": true,
"Published": true,
"ModifiedUtc": "2022-08-10T19:34:57.2678948Z",
"PublishedUtc": "2022-08-10T19:34:57.2716912Z",
"CreatedUtc": "2022-08-10T19:34:57.2678948Z",
"Owner": "48a8p8cbg3ksqvyd14d75x9a59",
"Author": "admin",
"TitlePart": {
"Title": "TestFreeProduct"
},
"AutoroutePart": {
"Path": "testfreeproduct",
"SetHomepage": false,
"Disabled": false,
"RouteContainedItems": false,
"Absolute": false
},
"HtmlBodyPart": {
"Html": ""
},
"ProductPart": {
"Sku": "TESTFREEPRODUCT"
},
"PricePart": {
"Price": {
"value": 0.0,
"currency": "USD"
}
},
"InventoryPart": {
"Inventory": {
"TESTFREEPRODUCT": 5
},
"InventoryKeys": [
"TESTFREEPRODUCT"
],
"AllowsBackOrder": {
"Value": true
},
"IgnoreInventory": {
"Value": false
},
"MaximumOrderQuantity": {
"Value": 2.0
},
"MinimumOrderQuantity": {
"Value": 1.0
},
"OutOfStockMessage": {
"Html": "A professional out of stock message."
},
"ProductSku": "TESTFREEPRODUCT"
},
"Product": {}
}
]
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,11 @@ await _taxProviders.GetFirstApplicableProviderAsync(promotionAndTaxContext) is {
}
}

return (viewModelLineItems, viewModelLineItems.CalculateTotals().Single());
var total = viewModelLineItems.CalculateTotals().Any()
? viewModelLineItems.CalculateTotals().Single()
: new Amount(0, lineItems.First().LinePrice.Currency);

return (viewModelLineItems, total);
}

private static IEnumerable<DiscountInformation> GetDiscounts(
Expand Down
77 changes: 66 additions & 11 deletions src/Modules/OrchardCore.Commerce/Services/PaymentService.cs
Original file line number Diff line number Diff line change
@@ -1,20 +1,25 @@
using Lombiq.HelpfulLibraries.OrchardCore.DependencyInjection;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Localization;
using Newtonsoft.Json.Linq;
using OrchardCore.Commerce.Abstractions;
using OrchardCore.Commerce.Constants;
using OrchardCore.Commerce.Extensions;
using OrchardCore.Commerce.Models;
using OrchardCore.Commerce.MoneyDataType;
using OrchardCore.Commerce.Promotion.Extensions;
using OrchardCore.Commerce.Tax.Extensions;
using OrchardCore.Commerce.ViewModels;
using OrchardCore.ContentManagement;
using OrchardCore.ContentManagement.Display;
using OrchardCore.DisplayManagement.ModelBinding;
using OrchardCore.Entities;
using OrchardCore.Mvc.Utilities;
using OrchardCore.Settings;
using OrchardCore.Users;
using Stripe;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using static OrchardCore.Commerce.Constants.ContentTypes;
Expand All @@ -29,12 +34,13 @@ public class PaymentService : IPaymentService
private readonly IShoppingCartHelpers _shoppingCartHelpers;
private readonly ISiteService _siteService;
private readonly UserManager<IUser> _userManager;
private readonly IStringLocalizer T;
private readonly IRegionService _regionService;
private readonly Lazy<IUserService> _userServiceLazy;
private readonly IPaymentIntentPersistence _paymentIntentPersistence;
private readonly IShoppingCartPersistence _shoppingCartPersistence;
private readonly IHttpContextAccessor _hca;
private readonly IUpdateModelAccessor _updateModelAccessor;
private readonly IContentItemDisplayManager _contentItemDisplayManager;

// We need all of them.
#pragma warning disable S107 // Methods should not have too many parameters
Expand All @@ -46,7 +52,9 @@ public PaymentService(
IRegionService regionService,
Lazy<IUserService> userServiceLazy,
IPaymentIntentPersistence paymentIntentPersistence,
IShoppingCartPersistence shoppingCartPersistence)
IShoppingCartPersistence shoppingCartPersistence,
IUpdateModelAccessor updateModelAccessor,
IContentItemDisplayManager contentItemDisplayManager)
#pragma warning restore S107 // Methods should not have too many parameters
{
_stripePaymentService = stripePaymentService;
Expand All @@ -57,7 +65,8 @@ public PaymentService(
_userManager = services.UserManager.Value;
_regionService = regionService;
_userServiceLazy = userServiceLazy;
T = services.StringLocalizer.Value;
_updateModelAccessor = updateModelAccessor;
_contentItemDisplayManager = contentItemDisplayManager;
_paymentIntentPersistence = paymentIntentPersistence;
_shoppingCartPersistence = shoppingCartPersistence;
_hca = services.HttpContextAccessor.Value;
Expand Down Expand Up @@ -107,7 +116,8 @@ await _contentManager.NewAsync(Order),
var stripeApiSettings = (await _siteService.GetSiteSettingsAsync()).As<StripeApiSettings>();
var initPaymentIntent = new PaymentIntent();
if (!string.IsNullOrEmpty(stripeApiSettings.PublishableKey) &&
!string.IsNullOrEmpty(stripeApiSettings.SecretKey))
!string.IsNullOrEmpty(stripeApiSettings.SecretKey) &&
total.Value > 0)
{
var paymentIntentId = _paymentIntentPersistence.Retrieve();
initPaymentIntent = await _stripePaymentService.InitializePaymentIntentAsync(paymentIntentId);
Expand Down Expand Up @@ -159,8 +169,8 @@ public async Task FinalModificationOfOrderAsync(ContentItem order)

await userService.AlterUserSettingAsync(user, UserAddresses, contentItem =>
{
var part = contentItem.ContainsKey(nameof(UserAddressesPart))
? contentItem[nameof(UserAddressesPart)].ToObject<UserAddressesPart>()!
var part = contentItem.TryGetValue(nameof(UserAddressesPart), out var partJson)
? partJson.ToObject<UserAddressesPart>()!
: new UserAddressesPart();

part.BillingAndShippingAddressesMatch.Value = isSame;
Expand All @@ -169,10 +179,6 @@ await userService.AlterUserSettingAsync(user, UserAddresses, contentItem =>
});
}

order.DisplayText = T["Order {0}", order.As<OrderPart>().OrderId.Text];

await _contentManager.UpdateAsync(order);

var currentShoppingCart = await _shoppingCartPersistence.RetrieveAsync();
currentShoppingCart?.Items?.Clear();

Expand All @@ -182,4 +188,53 @@ await userService.AlterUserSettingAsync(user, UserAddresses, contentItem =>
// Set back to default, because a new payment intent should be created on the next checkout.
_paymentIntentPersistence.Store(paymentIntentId: string.Empty);
}

public async Task<ContentItem> CreateNoPaymentOrderFromShoppingCartAsync()
{
var currentShoppingCart = await _shoppingCartPersistence.RetrieveAsync();

var order = await _contentManager.NewAsync(Order);
if (await UpdateOrderWithDriversAsync(order))
{
return null;
}

var lineItems = await _stripePaymentService.CreateOrderLineItemsAsync(currentShoppingCart);

var cartViewModel = await _shoppingCartHelpers.CreateShoppingCartViewModelAsync(
shoppingCartId: null,
order.As<OrderPart>().ShippingAddress.Address,
order.As<OrderPart>().BillingAddress.Address);

if (!cartViewModel.Totals.Any() || cartViewModel.Totals.Any(total => total.Value > 0))
{
return null;
}

order.Alter<OrderPart>(orderPart =>
{
// Shopping cart
orderPart.LineItems.SetItems(lineItems);

orderPart.Status.Text = OrderStatuses.Pending.HtmlClassify();

// Store the current applicable discount info, so they will be available in the future.
orderPart.AdditionalData.SetDiscountsByProduct(cartViewModel
.Lines
.Where(line => line.AdditionalData.GetDiscounts().Any())
.ToDictionary(
line => line.ProductSku,
line => line.AdditionalData.GetDiscounts()));
});

await _contentManager.CreateAsync(order);

return order;
}

private async Task<bool> UpdateOrderWithDriversAsync(ContentItem order)
{
await _contentItemDisplayManager.UpdateEditorAsync(order, _updateModelAccessor.ModelUpdater, isNew: false);
return _updateModelAccessor.ModelUpdater.GetModelErrorMessages().Any();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,9 @@ private async Task<ShoppingCartViewModel> CreateShoppingCartViewModelAsync(
line.UnitPrice = line.UnitPrice.GetRounded();
}

model.Totals.AddRange(totals.Round());
model.Totals.AddRange(
totals.Any() ? totals.Round() : new List<Amount> { new Amount(0, lines.First().LinePrice.Currency) });

model.Headers.AddRange(headers);
model.Lines.AddRange(lines);

Expand Down
Loading