Created
June 28, 2016 08:09
-
-
Save MattisOlsson/1330e633592cc72f6bf6214de488937b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using EPiServer.ServiceLocation; | |
using Geta.EPi.Checkout.Core.Infrastructure.Exceptions; | |
using Mediachase.Commerce.Orders; | |
using Mediachase.Commerce.Website; | |
using Mediachase.Commerce.Website.Helpers; | |
namespace Geta.EPi.Checkout.Core.Services | |
{ | |
/// <summary> | |
/// Service for processing a payment transaction. | |
/// </summary> | |
[ServiceConfiguration(typeof(IPaymentService), Lifecycle = ServiceInstanceScope.Singleton)] | |
public class PaymentService : IPaymentService | |
{ | |
private readonly Func<string, CartHelper> _cartHelper; | |
public PaymentService(Func<string, CartHelper> cartHelper) | |
{ | |
_cartHelper = cartHelper; | |
} | |
/// <summary> | |
/// Prepares cart for payment - adds payment data to the cart. Should be run before CartCheckOut workflow. | |
/// </summary> | |
/// <param name="method">The payment method to use for payment.</param> | |
public void PreparePayment(IPaymentOption method) | |
{ | |
var cart = _cartHelper(Mediachase.Commerce.Orders.Cart.DefaultName).Cart; | |
if (!cart.OrderForms.Any()) | |
{ | |
cart.OrderForms.AddNew(); | |
} | |
var payment = method.PreProcess(cart.OrderForms[0]); | |
if (payment == null) | |
{ | |
throw new PaymentPreProcessException(); | |
} | |
cart.OrderForms[0].Payments.Clear(); | |
cart.OrderForms[0].Payments.Add(payment); | |
cart.AcceptChanges(); | |
} | |
/// <summary> | |
/// Processes the provided payment - prepares and completes payment by single call. | |
/// </summary> | |
/// <param name="method">The payment to process.</param> | |
/// <returns>Service result indicating whether the processing was successfull or not.</returns> | |
[Obsolete("Use PreparePayment and CompletePayment methods instead. ProcessPayment just calls PreparePayment and CompletePayment sequentially. It ignores CartCheckOut workflow.")] | |
public virtual void ProcessPayment(IPaymentOption method) | |
{ | |
PreparePayment(method); | |
CompletePayment(method); | |
} | |
/// <summary> | |
/// Updates cart after payment processing. Should be run after CartCheckOut workflow when payment to 3rd party completed. | |
/// </summary> | |
/// <param name="method">The payment method to use for payment completion.</param> | |
public void CompletePayment(IPaymentOption method) | |
{ | |
var cart = _cartHelper(Mediachase.Commerce.Orders.Cart.DefaultName).Cart; | |
method.PostProcess(cart.OrderForms[0]); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment