Exemplo n.º 1
0
        /// <summary>
        /// Void transaction
        /// </summary>
        /// <param name="payment"></param>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        public TransactionResult VoidTransaction(IPayment payment, string accessToken)
        {
            var result = new TransactionResult();

            if (!Configuration.IsValid())
            {
                throw new Exception("Dintero configuration is not valid!");
            }

            var url = DinteroAPIUrlHelper.GetTransactionVoidUrl(payment.TransactionID);

            if (!string.IsNullOrWhiteSpace(url))
            {
                try
                {
                    result = SendTransactionRequest(url, "Bearer", accessToken, null,
                        new List<string> {"AUTHORIZATION_VOIDED"});
                }
                catch (Exception e)
                {
                    Logger.Error("An error occurred during voiding transaction.", e);
                    throw;
                }

            }

            return result;
        }
Exemplo n.º 2
0
        /// <summary>
        /// Refund transaction
        /// </summary>
        /// <param name="payment"></param>
        /// <param name="returnForms"></param>
        /// <param name="currency"></param>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        public TransactionResult RefundTransaction(IPayment payment, IEnumerable<IOrderForm> returnForms,
            Currency currency, string accessToken)
        {
            var result = new TransactionResult();

            if (!Configuration.IsValid())
            {
                throw new Exception("Dintero configuration is not valid!");
            }

            var url = DinteroAPIUrlHelper.GetTransactionRefundUrl(payment.TransactionID);

            if (!string.IsNullOrWhiteSpace(url))
            {
                try
                {
                    var transaction = GetTransactionDetails(payment.TransactionID, accessToken);

                    if (transaction == null)
                    {
                        throw new Exception("Dintero transaction can't be loaded!");
                    }

                    var request = new DinteroRefundRequest
                    {
                        Amount = CurrencyHelper.CurrencyToInt(payment.Amount, currency.CurrencyCode),
                        Reason = "Refund"
                    };

                    var returnForm = GetCurrentReturnForm(returnForms, transaction);

                    if (returnForm != null)
                    {
                        request.Items = ConvertRefundOrderLineItems(returnForm, transaction, currency);
                    }

                    result = SendTransactionRequest(url, "Bearer", accessToken, request,
                        new List<string> {"PARTIALLY_REFUNDED", "PARTIALLY_CAPTURED_REFUNDED", "REFUNDED"});
                }
                catch (Exception e)
                {
                    Logger.Error("An error occurred during refunding transaction.", e);
                    throw;
                }

            }

            return result;
        }
Exemplo n.º 3
0
        /// <summary>
        /// Capture transaction
        /// </summary>
        /// <param name="payment"></param>
        /// <param name="purchaseOrder"></param>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        public TransactionResult CaptureTransaction(IPayment payment, IPurchaseOrder purchaseOrder, string accessToken, bool skipItems = false)
        {
            var result = new TransactionResult();

            if (!Configuration.IsValid())
            {
                throw new Exception("Dintero configuration is not valid!");
            }

            var url = DinteroAPIUrlHelper.GetTransactionCaptureUrl(payment.TransactionID);

            if (!string.IsNullOrWhiteSpace(url))
            {
                try
                {
                    var request = new DinteroCaptureRequest
                    {
                        Amount = CurrencyHelper.CurrencyToInt(payment.Amount, purchaseOrder.Currency.CurrencyCode),
                        CaptureReference = purchaseOrder.OrderNumber,
                        Items = new List<DinteroOrderLine>()
                    };

                    if (!skipItems)
                    {
                        request.Items = ConvertOrderLineItems(purchaseOrder.Forms, purchaseOrder.Currency);
                    }

                    result = SendTransactionRequest(url, "Bearer", accessToken, request, new List<string> {"CAPTURED"});
                }
                catch (Exception e)
                {
                    Logger.Error("An error occurred during capturing transaction. ", e);
                    throw;
                }

            }

            return result;
        }
Exemplo n.º 4
0
        /// <summary>
        /// Retrieve access token and create a transaction with the order details
        /// </summary>
        /// <returns></returns>
        public string GetAccessToken()
        {
            string token = null;

            if (!Configuration.IsValid())
            {
                throw new Exception("Dintero configuration is not valid!");
            }

            var url = DinteroAPIUrlHelper.GetAuthUrl(Configuration.AccountId);

            if (!string.IsNullOrWhiteSpace(url))
            {
                try
                {
                    var response = SendRequest<DinteroAuthResponse>(url,
                        $"{Configuration.ClientId}:{Configuration.ClientSecretId}", "Basic",
                        new
                        {
                            grant_type = "client_credentials",
                            audience = DinteroAPIUrlHelper.GetAccountUrl(Configuration.AccountId)
                        });

                    if (response != null)
                    {
                        token = response.AccessToken;
                    }
                }
                catch (Exception e)
                {
                    Logger.Error("An error occurred during requesting access token.", e);
                    throw;
                }

            }

            return token;
        }
Exemplo n.º 5
0
        /// <summary>
        /// Retrieve transaction details
        /// </summary>
        /// <param name="transactionId"></param>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        public DinteroTransactionActionResponse GetTransactionDetails(string transactionId, string accessToken)
        {
            var result = new DinteroTransactionActionResponse();

            if (!Configuration.IsValid())
            {
                throw new Exception("Dintero configuration is not valid!");
            }

            var url = DinteroAPIUrlHelper.GetTransactionDetailsUrl(transactionId);

            if (!string.IsNullOrWhiteSpace(url))
            {
                try
                {
                    var response = (JObject)SendRequest<object>(url, accessToken, requestMethod: "GET");

                    result.Id = response["id"]?.ToString().ToUpper();
                    result.Currency = response["currency"]?.ToString().ToUpper();
                    result.Status = response["status"]?.ToString().ToUpper();
                    result.Items = response["items"]?.ToObject<List<DinteroOrderLine>>();
                    result.Events = new List<DinteroTransactionEvent>();
                    result.PaymentProduct = response["payment_product"]?.ToString().ToLower();

                    var events = response["events"];
                    if (events != null)
                    {
                        foreach (var transactionEvent in events)
                        {
                            var eventObj = new DinteroTransactionEvent
                            {
                                Id = transactionEvent["id"]?.ToString(),
                                Event = transactionEvent["event"]?.ToString().ToUpper(),
                                Items = response["items"]?.ToObject<List<DinteroOrderLine>>(),
                                Success = response["success"]?.ToString().ToLower() == "true"
                            };

                            if (int.TryParse(response["amount"]?.ToString(), out var eventAmount))
                            {
                                eventObj.Amount = eventAmount;
                            }

                            result.Events.Add(eventObj);
                        }
                    }

                    if (int.TryParse(response["amount"]?.ToString(), out var amount))
                    {
                        result.Amount = amount;
                    }

                }
                catch (Exception e)
                {
                    Logger.Error("An error occurred during capturing transaction.", e);
                    throw;
                }

            }

            return result;
        }
Exemplo n.º 6
0
        /// <summary>
        /// Create Dintero session
        /// </summary>
        /// <param name="payment"></param>
        /// <param name="currentCart"></param>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        public DinteroCreateSessionResponse CreateCheckoutSession(IPayment payment, ICart currentCart,
            string accessToken, string trackingNumber = "")
        {
            DinteroCreateSessionResponse sessionData = null;

            if (Configuration.IsValid() && !string.IsNullOrWhiteSpace(accessToken))
            {
                var url = DinteroAPIUrlHelper.GetNewSessionUrl();

                if (!Configuration.IsValid())
                {
                    throw new Exception("Dintero configuration is not valid!");
                }

                try
                {
                    var orderForm = currentCart.Forms.FirstOrDefault(f => f.Payments.Contains(payment));

                    if (orderForm != null)
                    {
                        var shippingAddress = orderForm.Shipments.First().ShippingAddress;

                        var orderNumber = string.IsNullOrEmpty(trackingNumber) ? _orderNumberGenerator.GenerateOrderNumber(currentCart): trackingNumber;

                        var request = new DinteroCreateSessionRequest
                        {
                            UrlSetting =
                                new DinteroUrlSetting
                                {
                                    ReturnUrl =
                                        UriUtil.GetUrlFromStartPageReferenceProperty("DinteroPaymentPage", true),
                                    CallbackUrl =
                                        UriUtil.GetUrlFromStartPageReferenceProperty("DinteroPaymentPage", true)
                                },
                            Customer = new DinteroCustomer
                            {
                                Email = payment.BillingAddress.Email,
                                PhoneNumber = payment.BillingAddress.DaytimePhoneNumber
                            },
                            Order = new DinteroOrder
                            {
                                Amount =
                                    CurrencyHelper.CurrencyToInt(payment.Amount, currentCart.Currency.CurrencyCode),
                                Currency = currentCart.Currency.CurrencyCode,
                                MerchantReference = orderNumber,
                                BillingAddress =
                                    new DinteroAddress
                                    {
                                        FirstName = payment.BillingAddress.FirstName,
                                        LastName = payment.BillingAddress.LastName,
                                        AddressLine =
                                            $"{payment.BillingAddress.Line1} {payment.BillingAddress.Line2}",
                                        PostalCode = payment.BillingAddress.PostalCode,
                                        PostalPlace = payment.BillingAddress.City,
                                        Country = payment.BillingAddress.CountryCode
                                    },
                                ShippingAddress = new DinteroAddress
                                {
                                    FirstName = shippingAddress.FirstName,
                                    LastName = shippingAddress.LastName,
                                    AddressLine = $"{shippingAddress.Line1} {shippingAddress.Line2}",
                                    PostalCode = shippingAddress.PostalCode,
                                    PostalPlace = shippingAddress.City,
                                    Country = shippingAddress.CountryCode
                                },
                                Items = ConvertOrderLineItems(currentCart.Forms, currentCart.Currency),
                                PartialPayment = false,
                                Store = new DinteroStore
                                {
                                    Id = currentCart != null && currentCart.GetFirstShipment() != null ? currentCart.GetFirstShipment().WarehouseCode: ""
                                }
                            },
                            ProfileId = Configuration.ProfileId
                        };

                        request.Order.VatAmount = request.Order.Items.Sum(item => item.VatAmount);
                        request.Order.PartialPayment = request.Order.Amount != request.Order.Items.Sum(item => item.Amount);

                        sessionData = SendRequest<DinteroCreateSessionResponse>(url, accessToken, "Bearer", request);
                    }
                }
                catch (Exception e)
                {
                    Logger.Error("An error occurred during initializing payment session.", e);
                    throw;
                }

            }

            return sessionData;
        }