public async Task <IActionResult> ViewPaymentRequest(string id)
        {
            var result = await _PaymentRequestService.GetPaymentRequest(id, GetUserId());

            if (result == null)
            {
                return(NotFound());
            }
            result.HubPath = PaymentRequestHub.GetHubPath(this.Request);
            return(View(result));
        }
        public async Task <IActionResult> PayPaymentRequest(string payReqId, bool redirectToInvoice = true,
                                                            decimal?amount = null, CancellationToken cancellationToken = default)
        {
            if (amount.HasValue && amount.Value <= 0)
            {
                return(BadRequest("Please provide an amount greater than 0"));
            }

            var result = await _PaymentRequestService.GetPaymentRequest(payReqId, GetUserId());

            if (result == null)
            {
                return(NotFound());
            }

            if (result.Archived)
            {
                if (redirectToInvoice)
                {
                    return(RedirectToAction("ViewPaymentRequest", new { Id = payReqId }));
                }

                return(BadRequest("Payment Request cannot be paid as it has been archived"));
            }

            result.HubPath = PaymentRequestHub.GetHubPath(Request);
            if (result.AmountDue <= 0)
            {
                if (redirectToInvoice)
                {
                    return(RedirectToAction("ViewPaymentRequest", new { Id = payReqId }));
                }

                return(BadRequest("Payment Request has already been settled."));
            }

            if (result.ExpiryDate.HasValue && DateTime.UtcNow >= result.ExpiryDate)
            {
                if (redirectToInvoice)
                {
                    return(RedirectToAction("ViewPaymentRequest", new { Id = payReqId }));
                }

                return(BadRequest("Payment Request has expired"));
            }

            var stateAllowedToDisplay = new HashSet <InvoiceState>
            {
                new InvoiceState(InvoiceStatusLegacy.New, InvoiceExceptionStatus.None),
                new InvoiceState(InvoiceStatusLegacy.New, InvoiceExceptionStatus.PaidPartial),
            };
            var currentInvoice = result
                                 .Invoices
                                 .FirstOrDefault(invoice => stateAllowedToDisplay.Contains(invoice.State));

            if (currentInvoice != null)
            {
                if (redirectToInvoice)
                {
                    return(RedirectToAction("Checkout", "UIInvoice", new { currentInvoice.Id }));
                }

                return(Ok(currentInvoice.Id));
            }

            if (result.AllowCustomPaymentAmounts && amount != null)
            {
                amount = Math.Min(result.AmountDue, amount.Value);
            }
            else
            {
                amount = result.AmountDue;
            }

            var pr = await _PaymentRequestRepository.FindPaymentRequest(payReqId, null, cancellationToken);

            var blob  = pr.GetBlob();
            var store = pr.StoreData;

            try
            {
                var redirectUrl = _linkGenerator.PaymentRequestLink(payReqId, Request.Scheme, Request.Host, Request.PathBase);

                var invoiceMetadata =
                    new InvoiceMetadata
                {
                    OrderId          = PaymentRequestRepository.GetOrderIdForPaymentRequest(payReqId),
                    PaymentRequestId = payReqId,
                    BuyerEmail       = result.Email
                };

                var invoiceRequest =
                    new CreateInvoiceRequest
                {
                    Metadata = invoiceMetadata.ToJObject(),
                    Currency = blob.Currency,
                    Amount   = amount.Value,
                    Checkout = { RedirectURL = redirectUrl }
                };

                var additionalTags = new List <string> {
                    PaymentRequestRepository.GetInternalTag(payReqId)
                };
                var newInvoice = await _InvoiceController.CreateInvoiceCoreRaw(invoiceRequest, store, Request.GetAbsoluteRoot(), additionalTags, cancellationToken);

                if (redirectToInvoice)
                {
                    return(RedirectToAction("Checkout", "UIInvoice", new { newInvoice.Id }));
                }

                return(Ok(newInvoice.Id));
            }
            catch (BitpayHttpException e)
            {
                return(BadRequest(e.Message));
            }
        }
        public async Task <IActionResult> PayPaymentRequest(string id, bool redirectToInvoice = true,
                                                            decimal?amount = null, CancellationToken cancellationToken = default)
        {
            if (amount.HasValue && amount.Value <= 0)
            {
                return(BadRequest("Please provide an amount greater than 0"));
            }
            var result = await _PaymentRequestService.GetPaymentRequest(id, GetUserId());

            if (result == null)
            {
                return(NotFound());
            }
            result.HubPath = PaymentRequestHub.GetHubPath(this.Request);
            if (result.AmountDue <= 0)
            {
                if (redirectToInvoice)
                {
                    return(RedirectToAction("ViewPaymentRequest", new { Id = id }));
                }

                return(BadRequest("Payment Request has already been settled."));
            }

            if (result.ExpiryDate.HasValue && DateTime.Now >= result.ExpiryDate)
            {
                if (redirectToInvoice)
                {
                    return(RedirectToAction("ViewPaymentRequest", new { Id = id }));
                }

                return(BadRequest("Payment Request has expired"));
            }

            var statusesAllowedToDisplay = new List <InvoiceStatus>()
            {
                InvoiceStatus.New
            };
            var validInvoice = result.Invoices.FirstOrDefault(invoice =>
                                                              Enum.TryParse <InvoiceStatus>(invoice.Status, true, out var status) &&
                                                              statusesAllowedToDisplay.Contains(status));

            if (validInvoice != null)
            {
                if (redirectToInvoice)
                {
                    return(RedirectToAction("Checkout", "Invoice", new { Id = validInvoice.Id }));
                }

                return(Ok(validInvoice.Id));
            }

            if (result.AllowCustomPaymentAmounts && amount != null)
            {
                amount = Math.Min(result.AmountDue, amount.Value);
            }
            else
            {
                amount = result.AmountDue;
            }


            var pr = await _PaymentRequestRepository.FindPaymentRequest(id, null);

            var blob  = pr.GetBlob();
            var store = pr.StoreData;

            try
            {
                var redirectUrl = Request.GetDisplayUrl().TrimEnd("/pay", StringComparison.InvariantCulture)
                                  .Replace("hub?id=", string.Empty, StringComparison.InvariantCultureIgnoreCase);
                var newInvoiceId = (await _InvoiceController.CreateInvoiceCore(new CreateInvoiceRequest()
                {
                    OrderId = $"{PaymentRequestRepository.GetOrderIdForPaymentRequest(id)}",
                    Currency = blob.Currency,
                    Price = amount.Value,
                    FullNotifications = true,
                    BuyerEmail = result.Email,
                    RedirectURL = redirectUrl,
                }, store, HttpContext.Request.GetAbsoluteRoot(),
                                                                               new List <string>()
                {
                    PaymentRequestRepository.GetInternalTag(id)
                },
                                                                               cancellationToken: cancellationToken))
                                   .Data.Id;

                if (redirectToInvoice)
                {
                    return(RedirectToAction("Checkout", "Invoice", new { Id = newInvoiceId }));
                }

                return(Ok(newInvoiceId));
            }
            catch (BitpayHttpException e)
            {
                return(BadRequest(e.Message));
            }
        }