示例#1
0
        public async Task <IEnumerable <TransactionDTO> > Execute(PaymentModel payment)
        {
            var customer = await _paymentRepository.GetLastTransaction(payment.OrderId);

            var service = new RefundService();

            var options = new RefundCreateOptions
            {
                Charge = customer.ExternalId,
            };

            var orderInfo = new PaymentModel {
                UserId = customer.UserId, VendorId = customer.VendorId, OrderId = customer.OrderId, Amount = customer.Amount
            };

            var transaction = await _retryHelper.RetryIfThrown(async() =>
            {
                var result = await service.CreateAsync(options);
                var test   = _mappingProvider.GetMappingOperation(PaymentServiceConstants.PaymentMappingType.Stripe_Refund)
                             .Map(PaymentServiceConstants.PaymentType.Refund, orderInfo, result, result.Created);
                return(test);
            }, PaymentServiceConstants.PaymentType.Refund, orderInfo, PaymentServiceConstants.isSucceeded.Succeeded);

            return(await _paymentRepository.CreateTransactions(transaction));
        }
示例#2
0
        public ActionResult Refund()
        {
            try
            {
                StripeConfiguration.ApiKey            = key;
                StripeConfiguration.MaxNetworkRetries = 2;

                var refunds       = new RefundService();
                var refundOptions = new RefundCreateOptions
                {
                    PaymentIntent = paymentIntent
                };
                var refund = refunds.Create(refundOptions);

                return(View("OrderStatus"));
            }
            catch (StripeException e)
            {
                var x = new
                {
                    status  = "Failed",
                    message = e.Message
                };
                return(this.Json(x));
            }
        }
示例#3
0
        public IActionResult CancelOrder(int id)
        {
            OrderHeader orderHeader = _unitOfWork.OrderHeader.GetFirstOrDefault(u => u.Id == id);

            if (orderHeader.PaymentStatus == SD.StatusApproved)
            {
                //Stripe entities
                var options = new RefundCreateOptions
                {
                    Amount = Convert.ToInt32(orderHeader.OrderTotal * 100),
                    Reason = RefundReasons.RequestedByCustomer,
                    Charge = orderHeader.TransactionId
                };
                var    service = new RefundService();
                Refund refund  = service.Create(options);
                orderHeader.OrderStatus   = SD.StatusRefunded;
                orderHeader.PaymentStatus = SD.StatusRefunded;
                //after giving them the refund in stripe change the orderHeader niformation accordingly
            }
            //if unable to refund just cancel the order.
            else
            {
                orderHeader.OrderStatus   = SD.StatusCancelled;
                orderHeader.PaymentStatus = SD.StatusCancelled;
            }
            _unitOfWork.Save();
            return(RedirectToAction("Index"));
        }
示例#4
0
        public async void chargeGroceryAmount()
        {
            try
            {
                StripeConfiguration.SetApiKey("sk_test_Q5wSnyXL03yN0KpPaAMYttOb");
                var options = new RefundCreateOptions
                {
                    ChargeId = jobChargeId
                };
                var    service = new RefundService();
                Refund refund  = service.Create(options);

                double amount = Convert.ToDouble(totalAmounts);


                var charge = new ChargeCreateOptions
                {
                    Amount     = Convert.ToInt32(amount * 100), // In cents, not dollars, times by 100 to convert
                    Currency   = "aud",                         // or the currency you are dealing with
                    CustomerId = "cus_Dxa4I8cQgAL7D7"           //Convert.ToString(userData["stripeCustomerId"]),
                };
                var services = new ChargeService();
                var response = services.Create(charge);

                await DisplayAlert("", "Successfully Charge Amount: " + amount, "Ok");
            }
            catch (Exception ex)
            {
                await DisplayAlert("", ExceptionManagement.LogException(ex), "Ok");
            }
        }
        public RefundServiceTest(
            StripeMockFixture stripeMockFixture,
            MockHttpClientFixture mockHttpClientFixture)
            : base(stripeMockFixture, mockHttpClientFixture)
        {
            this.service = new RefundService(this.StripeClient);

            this.createOptions = new RefundCreateOptions
            {
                Amount = 123,
                Charge = "ch_123",
            };

            this.updateOptions = new RefundUpdateOptions
            {
                Metadata = new Dictionary <string, string>
                {
                    { "key", "value" },
                },
            };

            this.listOptions = new RefundListOptions
            {
                Limit = 1,
            };
        }
示例#6
0
        public IActionResult CancelOrder(int id)
        {
            OrderHeader orderHeader = _unitOfWork.OrderHeader.GetFirstOrDefault(u => u.Id == id);

            if (orderHeader.PaymentStatus == SD.StatusApproved)
            {
                var options = new RefundCreateOptions
                {
                    Amount = Convert.ToInt32(orderHeader.OrderTotal * 100),
                    Reason = RefundReasons.RequestedByCustomer,
                    Charge = orderHeader.TransactionId
                };
                var    service = new RefundService();
                Refund refund  = service.Create(options);

                orderHeader.OrderStatus   = SD.StatusRefunded;
                orderHeader.PaymentStatus = SD.StatusRefunded;
            }
            else
            {
                orderHeader.OrderStatus   = SD.StatusCancelled;
                orderHeader.PaymentStatus = SD.StatusCancelled;
            }

            _unitOfWork.Save();
            return(RedirectToAction("Index"));
        }
        public ActionResult DeleteConfirmed(int id)
        {
            //Debug Purpose to see if we are getting the id
            Debug.WriteLine("I'm pulling data of " + id.ToString());

            //Get the specific Donation
            Donation donation = db.Donations.Find(id);

            //Refund the donated amount back to the user
            //Code Referenced from: https://stripe.com/docs/refunds
            StripeConfiguration.ApiKey = "sk_test_T3BF2ap8TTDpmetCKxF038r400HAf7zrj8";
            var refunds       = new RefundService();
            var refundOptions = new RefundCreateOptions
            {
                PaymentIntent = donation.donationReceiptId,
                Amount        = donation.donationAmount
            };
            var refund = refunds.Create(refundOptions);

            //Delete that specific Donation from the database
            db.Donations.Remove(donation);

            //Save the changes on the database
            db.SaveChanges();

            //Go back to the list of Donation to see the removed Donation
            return(RedirectToAction("Index"));
        }
示例#8
0
        public string Refund(string toggleRefund)
        {   //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
            //sk_test_51Gzaa1HAh8lBnQxza9cOAzY7LbfgQ4FWX2sYqiuHsoVWJg4mNDppueQkAVd0XIPU4GhcrNBca8aemNgr24m4jDv200ooFw0Bhz
            StripeConfiguration.ApiKey = "sk_test_51Gzaa1HAh8lBnQxza9cOAzY7LbfgQ4FWX2sYqiuHsoVWJg4mNDppueQkAVd0XIPU4GhcrNBca8aemNgr24m4jDv200ooFw0Bhz";
            var msg = "";

            if (toggleRefund == "refund")
            {
                var refunds       = new RefundService();
                var refundOptions = new RefundCreateOptions
                {
                    PaymentIntent = "pi_1GzxFMHAh8lBnQxzpA2OSATN"
                };
                var refund = refunds.Create(refundOptions);
                msg = "Payment refunded successfully";
            }

            else if (toggleRefund == "cancelRefund")
            {
                var service = new PaymentIntentService();
                var options = new PaymentIntentCancelOptions {
                };
                var intent  = service.Cancel("pi_1GzxFMHAh8lBnQxzpA2OSATN", options);
                msg = "Payment refund cancelled";
            }
            //ViewBag.message = msg;
            return(msg);
        }
示例#9
0
        public IActionResult CancelOrder(int id)
        {
            var orderHeader = _unitOfWork.OrderHeader.FirstOrDefault(c => c.Id == id);

            //We want refund if only the status was approved for the initial payment because if the status was for a delayed company we dont want to process a refund for them
            if (orderHeader.PaymentStatus == SD.StatusApproved)
            {
                var options = new RefundCreateOptions
                {
                    Amount = Convert.ToInt32(orderHeader.OrderTotal * 100),
                    Reason = RefundReasons.RequestedByCustomer,
                    Charge = orderHeader.TransactionId
                };
                var service = new RefundService();
                var refund  = service.Create(options);

                orderHeader.OrderStatus   = SD.StatusCancelled;
                orderHeader.PaymentStatus = SD.StatusCancelled;
            }
            else
            {
                orderHeader.OrderStatus   = SD.StatusCancelled;
                orderHeader.PaymentStatus = SD.StatusCancelled;
            }
            _unitOfWork.Save();
            return(RedirectToAction(nameof(Index)));
        }
示例#10
0
        public IActionResult OnPostOrderRefund(int orderId)
        {
            OrderHeader orderHeader = _unitOfWork.OrderHeader.GetFirstOrDefault(o => o.Id == orderId);

            //refund the amount
            //go to stripe and find the documentation in refund
            //copy the post call in refunds documentation
            // this is the code of refund
            var options = new RefundCreateOptions
            {
                Amount = Convert.ToInt32(orderHeader.OrderTotal * 100),
                Reason = RefundReasons.RequestedByCustomer,
                //something wrong with charge. I think that is ChargeId
                Charge = orderHeader.TransactionId
            };
            var service = new RefundService();

            //Refund refund = service.Create("myAPI coedes", refundOptions);
            Refund refund = service.Create(options);


            orderHeader.Status = SD.StatusRefunded;
            _unitOfWork.Save();

            return(RedirectToPage("ManageOrder"));
        }
        public override async Task <ApiResult> RefundPaymentAsync(PaymentProviderContext <StripeCheckoutSettings> ctx)
        {
            try
            {
                // We can only refund a captured charge, so make sure we have one
                // otherwise there is nothing we can do
                var chargeId = ctx.Order.Properties["stripeChargeId"];
                if (string.IsNullOrWhiteSpace(chargeId))
                {
                    return(null);
                }

                var secretKey = ctx.Settings.TestMode ? ctx.Settings.TestSecretKey : ctx.Settings.LiveSecretKey;

                ConfigureStripe(secretKey);

                var refundService       = new RefundService();
                var refundCreateOptions = new RefundCreateOptions()
                {
                    Charge = chargeId
                };

                var refund = refundService.Create(refundCreateOptions);
                var charge = refund.Charge ?? await new ChargeService().GetAsync(refund.ChargeId);

                // If we have a subscription then we'll cancel it as refunding an ctx.Order
                // should effecitvely undo any purchase
                if (!string.IsNullOrWhiteSpace(ctx.Order.Properties["stripeSubscriptionId"]))
                {
                    var subscriptionService = new SubscriptionService();
                    var subscription        = await subscriptionService.GetAsync(ctx.Order.Properties["stripeSubscriptionId"]);

                    if (subscription != null)
                    {
                        subscriptionService.Cancel(ctx.Order.Properties["stripeSubscriptionId"], new SubscriptionCancelOptions
                        {
                            InvoiceNow = false,
                            Prorate    = false
                        });
                    }
                }

                return(new ApiResult()
                {
                    TransactionInfo = new TransactionInfoUpdate()
                    {
                        TransactionId = GetTransactionId(charge),
                        PaymentStatus = GetPaymentStatus(charge)
                    }
                });
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "Stripe - RefundPayment");
            }

            return(ApiResult.Empty);
        }
示例#12
0
        public override ApiResult RefundPayment(OrderReadOnly order, StripeCheckoutSettings settings)
        {
            try
            {
                // We can only refund a captured charge, so make sure we have one
                // otherwise there is nothing we can do
                var chargeId = order.Properties["stripeChargeId"];
                if (string.IsNullOrWhiteSpace(chargeId))
                {
                    return(null);
                }

                var secretKey = settings.TestMode ? settings.TestSecretKey : settings.LiveSecretKey;

                ConfigureStripe(secretKey);

                var refundService       = new RefundService();
                var refundCreateOptions = new RefundCreateOptions()
                {
                    Charge = chargeId
                };

                var refund = refundService.Create(refundCreateOptions);
                var charge = refund.Charge ?? new ChargeService().Get(refund.ChargeId);

                // If we have a subscription then we'll cancel it as refunding an order
                // should effecitvely undo any purchase
                if (!string.IsNullOrWhiteSpace(order.Properties["stripeSubscriptionId"]))
                {
                    var subscriptionService = new SubscriptionService();
                    var subscription        = subscriptionService.Get(order.Properties["stripeSubscriptionId"]);
                    if (subscription != null)
                    {
                        subscriptionService.Cancel(order.Properties["stripeSubscriptionId"], new SubscriptionCancelOptions
                        {
                            InvoiceNow = false,
                            Prorate    = false
                        });
                    }
                }

                return(new ApiResult()
                {
                    TransactionInfo = new TransactionInfoUpdate()
                    {
                        TransactionId = GetTransactionId(charge),
                        PaymentStatus = GetPaymentStatus(charge)
                    }
                });
            }
            catch (Exception ex)
            {
                Vendr.Log.Error <StripeCheckoutOneTimePaymentProvider>(ex, "Stripe - RefundPayment");
            }

            return(ApiResult.Empty);
        }
示例#13
0
        public virtual async Task <Refund> Create(string chargeId, RefundCreateOptions options = null)
        {
            var url = string.Format("{0}/{1}/refunds", Urls.Charges, chargeId);

            url = this.ApplyAllParameters(options, url, false);

            var response = await Requestor.Post(url);

            return(Mapper <Refund> .MapFromJson(response));
        }
示例#14
0
        public async Task <Refund> CreateRefundAsync(string chargeId)
        {
            var options = new RefundCreateOptions
            {
                Charge = chargeId,
            };

            var service = new Stripe.RefundService();

            return(await service.CreateAsync(options));
        }
示例#15
0
        public static Refund RefundPayment(string ChargerID)
        {
            StripeConfiguration.SetApiKey(SecretKey);
            var refundService = new RefundService();
            var refundOptions = new RefundCreateOptions
            {
                ChargeId = ChargerID,
            };
            Refund refund = refundService.Create(refundOptions);

            return(refund);
        }
        public async Task <ActionResult> RefundPayment([FromBody] string chargeId) //Full Refund, we can set up amount in refund options for partial refund
        {
            var refunds       = new RefundService();
            var refundOptions = new RefundCreateOptions
            {
                Charge = chargeId
                         //Amount = 1000
            };
            var refund = await refunds.CreateAsync(refundOptions);

            return(new OkObjectResult(new { Success = "true" }));
        }
示例#17
0
        public async Task <RefundDto> CreateRefund(RefundCreateDto dto)
        {
            var options = new RefundCreateOptions
            {
                ChargeId = dto.ChargeId,
                Amount   = dto.Amount,
                Reason   = RefundReasons.Fraudulent
            };
            var service = new RefundService();

            return(RefundMapper.MapRefundToRefundDto(await service.CreateAsync(options)));
        }
示例#18
0
        private Refund RefundCharge(string chargeId)
        {
            StripeConfiguration.ApiKey = _appKeys.StripeApiKey;
            var options = new RefundCreateOptions
            {
                Charge = chargeId,
            };
            var service = new RefundService();
            var refund  = service.Create(options);

            return(refund);
        }
        public async Task <IActionResult> StripeRefund(string paymentRef)
        {
            var payment = _context.Payments.SingleOrDefault(x => x.PaymentServiceRef == paymentRef);

            if (payment == null)
            {
                return(NotFound("Payment id not found"));
            }


            try
            {
                var refunds = new RefundService();


                var refundOptions = new RefundCreateOptions {
                    PaymentIntent = paymentRef
                };
                var refund = refunds.Create(refundOptions);
            }
            catch (Exception e)
            {
                return(BadRequest("Error refunding stripe"));
            }



            payment.ExtraDescription = "Refunded: " + payment.Amount;
            payment.RefundedAt       = Format.NorwayDateTimeNow();
            payment.Refunded         = true;


            _context.Update(payment);
            _context.SaveChanges();


            var relatedInvoice = _context.Invoices.SingleOrDefault(x => x.PaymentId == payment.Id);

            if (relatedInvoice == null)
            {
                return(Ok());
            }
            relatedInvoice.Paid     = false;
            relatedInvoice.Canceled = true;
            _context.Update(relatedInvoice);
            _context.SaveChanges();


            return(Ok());
        }
        public IActionResult CancelOrder(int id)
        {
            OrderHeader orderHeader = _unitofwork.OrderHeader.GetFirstOrDefault(u => u.Id == id);

            if (orderHeader.PaymentStatus == SD.StatusApproved)
            {
                var options = new RefundCreateOptions
                {
                    Amount = Convert.ToInt32(orderHeader.OrderTotal * 100),
                    Reason = RefundReasons.RequestedByCustomer,
                    Charge = orderHeader.TransactionId
                };
                try
                {
                    var    service = new RefundService();
                    Refund refund  = service.Create(options);
                }
                catch (Exception x)
                {
                }
                orderHeader.OrderStatus   = SD.StatusRefunded;
                orderHeader.PaymentStatus = SD.StatusRefunded;
            }
            else
            {
                orderHeader.OrderStatus   = SD.StatusCancelled;
                orderHeader.PaymentStatus = SD.StatusCancelled;
            }

            _unitofwork.Save();

            //code SMS for CancelOrder
            SmsTemplate smsTemplate = _db.SmsTemplates.Where(e => e.Id == Convert.ToInt32(EnSmsTemplate.CancelOrder)).FirstOrDefault();

            smsTemplate.Content = smsTemplate.Content.Replace("###Name###", orderHeader.Name);
            TwilioClient.Init(_twilioOptions.AccountSid, _twilioOptions.AuthToken);
            try
            {
                var message = MessageResource.Create(
                    from: new Twilio.Types.PhoneNumber(_twilioOptions.PhoneNumber),
                    to: new Twilio.Types.PhoneNumber(orderHeader.PhoneNumber),
                    body: smsTemplate.Content);
            }

            catch (Exception x)
            {
            }
            return(RedirectToAction("Index"));
        }
示例#21
0
        private Refund Refund(string chargeId, string stripeAccountId)
        {
            var refundService = new RefundService();
            var refundOptions = new RefundCreateOptions()
            {
                Charge = chargeId
            };

            refundOptions.RefundApplicationFee = true;
            Refund refund = refundService.Create(refundOptions, new RequestOptions {
                StripeAccount = stripeAccountId
            });

            return(refund);
        }
示例#22
0
        public IActionResult OnPostOrderRefund(int id)
        {
            OrderHeader orderHeader = _unitOfWork.OrderHeader.GetFirstOrDefault(o => o.Id == id);

            var options = new RefundCreateOptions()
            {
                Amount = Convert.ToInt32(orderHeader.OrderTotal * 100),
                Reason = RefundReasons.RequestedByCustomer
            };
            var    service = new RefundService();
            Refund refund  = service.Create(options);

            orderHeader.Status = SD.StatusRefounded;
            _unitOfWork.Save();
            return(RedirectToPage("OrderList"));
        }
示例#23
0
        public IActionResult OnPostOrderRefund(int orderId)
        {
            OrderHeader orderHeader = _unitOfWork.OrderHeader.GetFirstOrDefualt(s => s.Id == orderId);
            //refund amoount
            var options = new RefundCreateOptions
            {
                Amount = Convert.ToInt32(orderHeader.OrderTotal * 100),
                Reason = RefundReasons.RequestedByCustomer,
                Charge = orderHeader.TransactionId,
            };
            var    service = new RefundService();
            Refund refund  = service.Create(options);

            orderHeader.Status = SD.StatusRefunded;
            _unitOfWork.Save();
            return(RedirectToPage("ManagerOrder"));
        }
示例#24
0
        //post for Order Refund
        public IActionResult OnPostOrderRefund(int orderId)
        {
            OrderHeader orderHeader = _unitOfWork.OrderHeader.GetFirstOrDefault(o => o.Id == orderId);
            //refund amoount
            var options = new RefundCreateOptions
            {
                Amount   = Convert.ToInt32(orderHeader.OrderTotal * 100),
                Reason   = RefundReasons.RequestedByCustomer, //on customer requste we can put other options as well
                ChargeId = orderHeader.TransactionId          //trcking transaction id for refund
            };
            var    service = new RefundService();
            Refund refund  = service.Create(options);

            orderHeader.Status = SD.StatusRefunded;

            _unitOfWork.Save();
            return(RedirectToPage("ManageOrder"));
        }
示例#25
0
        public Refund Refund(decimal?payAmount,
                             string paymentId,
                             string userId,
                             long orderId,
                             long transactionId,
                             Guid correlationId)
        {
            var refunds       = new RefundService();
            var refundOptions = new RefundCreateOptions
            {
                PaymentIntent = paymentId,
                Amount        = (long)(payAmount * 100)
            };

            var refund = refunds.Create(refundOptions);

            return(refund);
        }
        public override ApiInfo RefundPayment(Order order, IDictionary <string, string> settings)
        {
            try
            {
                order.MustNotBeNull("order");
                settings.MustNotBeNull("settings");
                settings.MustContainKey("mode", "settings");
                settings.MustContainKey(settings["mode"] + "_secret_key", "settings");

                // We can only refund a captured charge, so make sure we have one
                // otherwise there is nothing we can do
                if (order.TransactionInformation.TransactionId == null)
                {
                    return(null);
                }

                var apiKey = settings[settings["mode"] + "_secret_key"];

                ConfigureStripe(apiKey);

                var refundService       = new RefundService();
                var refundCreateOptions = new RefundCreateOptions()
                {
                    Charge = order.TransactionInformation.TransactionId
                };

                var refund = refundService.Create(refundCreateOptions);
                var charge = refund.Charge;

                if (charge == null)
                {
                    var chargeService = new ChargeService();
                    charge = chargeService.Get(order.TransactionInformation.TransactionId);
                }

                return(new ApiInfo(charge.Id, GetPaymentState(charge)));
            }
            catch (Exception exp)
            {
                LoggingService.Instance.Error <Stripe>("Stripe(" + order.OrderNumber + ") - RefundPayment", exp);
            }

            return(null);
        }
示例#27
0
        public static TransactionResult ProcessRefund(TransactionRequest refundRequest, StripeSettings stripeSettings, ILogger logger)
        {
            InitStripe(stripeSettings, true);
            var refundService = new RefundService();
            var order         = refundRequest.Order;
            var address       = order.BillingAddressSerialized.To <Address>();

            GetFinalAmountDetails(refundRequest.Amount ?? refundRequest.Order.OrderTotal, refundRequest.Order.CurrencyCode, address, out _, out var amount);
            var refundOptions = new RefundCreateOptions
            {
                Charge = refundRequest.GetParameterAs <string>("chargeId"),
                Amount = 100 * (long)(amount),
            };
            var refund       = refundService.Create(refundOptions);
            var refundResult = new TransactionResult()
            {
                TransactionGuid    = Guid.NewGuid().ToString(),
                ResponseParameters = new Dictionary <string, object>()
                {
                    { "sourceTransferReversalId", refund.SourceTransferReversalId },
                    { "balanceTransactionId", refund.BalanceTransactionId },
                    { "chargeId", refund.ChargeId },
                    { "receiptNumber", refund.ReceiptNumber },
                },
                OrderGuid = refundRequest.Order.Guid,
                TransactionCurrencyCode = refund.Currency,
                TransactionAmount       = (decimal)refund.Amount / 100
            };

            if (refund.Status == "failed")
            {
                logger.Log <TransactionResult>(LogLevel.Warning, "The refund for Order#" + refundRequest.Order.Id + " by stripe failed." + refund.FailureReason);
                refundResult.Success   = false;
                refundResult.Exception = new Exception("An error occurred while processing refund");
                return(refundResult);
            }
            if (refund.Status == "succeeded")
            {
                refundResult.NewStatus = refundRequest.IsPartialRefund ? PaymentStatus.RefundedPartially : PaymentStatus.Refunded;
                refundResult.Success   = true;
            }

            return(refundResult);
        }
示例#28
0
        public async Task <IActionResult> OnPostOrderRefund(int orderId)
        {
            var orderHeader = await _unitOfWork.OrderHeaderRepository.GetFirstOrDefaultAsync(x => x.Id == orderId);

            // refund the amount
            var options = new RefundCreateOptions
            {
                Amount = Convert.ToInt32(orderHeader.OrderTotal * 100),
                Reason = RefundReasons.RequestedByCustomer,
                Charge = orderHeader.TransactionId,
            };
            var service = new RefundService();
            var refund  = service.Create(options);

            orderHeader.Status = Sd.StatusRefunded;
            await _unitOfWork.SaveAsync();

            return(RedirectToPage("ManageOrder"));
        }
示例#29
0
        public IActionResult OnPostOrderRefund(int orderId)
        {
            OrderHeader orderheader = _unitOfWork.OrderHeader.GetFirstOrDefault(o => o.Id == orderId);

            //Refund amount on Stripe
            var options = new RefundCreateOptions
            {
                Amount = Convert.ToInt32(orderheader.OrderTotal * 100),
                Reason = RefundReasons.RequestedByCustomer,
                Charge = orderheader.TransactionId
            };
            var service = new RefundService();

            service.Create(options);

            orderheader.Status = StaticDetails.StatusRefunded;
            _unitOfWork.Save();
            return(RedirectToPage("ManageOrder"));
        }
示例#30
0
        public async Task <IActionResult> OnPostCancelOrderAsync()
        {
            Models.Order orderFromDb = await _orderService.GetOrderSummaryByOrderId(OrderDetails.Order.Id);

            if (orderFromDb.OrderStatus == SD.OrderStatus.APPROVED ||
                orderFromDb.OrderStatus == SD.OrderStatus.PROCESSING) // Only refund when either of these conditions are met
            {
                RefundCreateOptions refundOptions = new RefundCreateOptions
                {
                    Amount = Convert.ToInt32(orderFromDb.OrderTotal * 100),
                    Reason = RefundReasons.RequestedByCustomer,
                    Charge = orderFromDb.TransactionId
                };

                RefundService refundService = new RefundService();
                Refund        refund        = refundService.Create(refundOptions);

                orderFromDb.OrderStatus   = SD.OrderStatus.REFUNDED;
                orderFromDb.PaymentStatus = SD.PaymentStatus.REFUNDED;
                orderFromDb.PaymentDate   = DateTime.Now;
                orderFromDb.UpdatedAt     = DateTime.Now;
                orderFromDb.UpdatedBy     = User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;
                orderFromDb.OrderActionId = (long)SD.OrderAction.REFUND;
            }
            else
            {
                orderFromDb.OrderStatus   = SD.OrderStatus.CANCELLED;
                orderFromDb.PaymentStatus = SD.PaymentStatus.CANCELLED;
                orderFromDb.UpdatedAt     = DateTime.Now;
                orderFromDb.UpdatedBy     = User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;
                orderFromDb.OrderActionId = (long)SD.OrderAction.CANCEL;
            }

            var isCancelSuccess = await _orderService.Update(orderFromDb);

            if (!isCancelSuccess)
            {
                ErrorMessage = $"Failed to {(orderFromDb.OrderActionId == (long)SD.OrderAction.REFUND ? "refund" : "cancel")} order.";
            }

            return(RedirectToPage());
        }