Exemplo n.º 1
0
        public override void ProcessCallback(Payment payment)
        {
            InitClient(payment);
            // BH: Normally, our payment processor would "ping" this endpoint.
            // However, we're going to do it from AJAX ourselves, thus negating the need for a Stripe webhook.
            var paymentIntentId = payment.PaymentProperties.First(p => p.Key == PaymentIntentKey).Value;

            // Just confirm the payment intent exists
            var paymentIntent = PaymentIntentService.Get(paymentIntentId);

            // Firstly: does the payment intent require manual confirmation?
            if (paymentIntent.ConfirmationMethod == "manual")
            {
                try {
                    paymentIntent = PaymentIntentService.Confirm(paymentIntent.Id);
                } catch {
                    throw new InvalidOperationException("Could not confirm payment intent");
                }
            }

            if (paymentIntent.Status != StripeStatus.Succeeded)
            {
                throw new InvalidOperationException("Payment intent capture not successful");
            }

            var transaction = paymentIntent.Charges.First();

            if (transaction.Currency != payment.PurchaseOrder.BillingCurrency.ISOCode.ToLower())
            {
                throw new InvalidOperationException($"The payment currency ({payment.PurchaseOrder.BillingCurrency.ISOCode.ToUpper()}) and the currency configured for the merchant account ({transaction.Currency.ToUpper()}) doesn't match. Make sure that the payment currency matches the currency selected in the merchant account.");
            }

            var paymentStatus = PaymentStatusCode.Declined;

            if (paymentIntent.Status == StripeStatus.Succeeded)
            {
                if (string.IsNullOrEmpty(transaction.Id))
                {
                    throw new ArgumentException(@"Charge ID must be present in the PaymentIntent object.");
                }
                payment.TransactionId = paymentIntent.Id;                 // This is used for
                paymentStatus         = PaymentStatusCode.Authorized;
            }

            payment.PaymentStatus = PaymentStatus.Get((int)paymentStatus);
            ProcessPaymentRequest(new PaymentRequest(payment.PurchaseOrder, payment));
            HttpContext.Current.Response.StatusCode = 200;
        }
Exemplo n.º 2
0
        public Session GetSessionBySessionId(string sessionId)
        {
            var res = sessions.Get(sessionId);

            res.PaymentIntent = paymentIntents.Get(res.PaymentIntentId);
            return(res);
        }
        public dynamic confirmPayment(ConfirmPaymentInfo confirmPaymentInfo)
        {
            string        stripeRedirectUrl    = String.IsNullOrEmpty(confirmPaymentInfo.RedirectUrl)? GetEnvironmentConfigVar(StripeConfigKey, this.configuration.GetValue <string>(StripeConfigRedirectUrl)) + "/Home/ConfirmPayment":confirmPaymentInfo.RedirectUrl;
            var           paymentIntentService = new PaymentIntentService();
            PaymentIntent paymentIntent        = null;

            try
            {
                if (confirmPaymentInfo.PaymentIntentId != null)
                {
                    paymentIntent = paymentIntentService.Get(confirmPaymentInfo.PaymentIntentId);
                    if (paymentIntent.Status == "requires_payment_method")
                    {
                        generatePaymentResponse(paymentIntent);
                    }
                    else
                    {
                        var confirmOptions = new PaymentIntentConfirmOptions {
                            ReturnUrl = stripeRedirectUrl
                        };
                        paymentIntent = paymentIntentService.Confirm(
                            confirmPaymentInfo.PaymentIntentId,
                            confirmOptions
                            );
                    }
                }
            }
            catch (StripeException e)
            {
                return(new { error = e.StripeError.Message });
            }
            return(generatePaymentResponse(paymentIntent));
        }
        private string ProcessWebhookRequest(Order order, HttpRequest request, IDictionary <string, string> settings)
        {
            var apiKey        = settings[settings["mode"] + "_secret_key"];
            var webhookSecret = settings[settings["mode"] + "_webhook_secret"];

            ConfigureStripe(apiKey);

            var stripeEvent = GetWebhookStripeEvent(request, webhookSecret);

            if (stripeEvent.Type == "payment_intent.amount_capturable_updated")  // Occurs when payments are not auto captured and funds are authorized
            {
                var paymentIntent = (PaymentIntent)stripeEvent.Data.Object.Instance;

                FinalizeOrUpdateOrder(order, paymentIntent);
            }
            else if (stripeEvent.Type.StartsWith("charge."))
            {
                var charge = (Charge)stripeEvent.Data.Object.Instance;

                if (!string.IsNullOrWhiteSpace(charge.PaymentIntentId))
                {
                    var paymentIntentService    = new PaymentIntentService();
                    var paymentIntentGetOptions = new PaymentIntentGetOptions {
                    };
                    var paymentIntent           = paymentIntentService.Get(charge.PaymentIntentId, paymentIntentGetOptions);

                    FinalizeOrUpdateOrder(order, paymentIntent);
                }
            }

            return(null);
        }
        public string GetClientSecret(string paymentIntentId)
        {
            var paymentIntent = _paymentIntentService.Get(paymentIntentId);
            var clientSecret  = paymentIntent.ClientSecret;

            return(clientSecret);
        }
        public ActionResult HandleCardPaymentComplete(StripePayment model)
        {
            StripeConfiguration.ApiKey = ConfigurationManager.AppSettings["Cashier:Stripe:Secret"];

            var paymentIntent = PaymentService.GetPaymentIntentByTransactionRef(model.TransactionReference);
            var service       = new PaymentIntentService();

            ExStripe.PaymentIntent stripePI = null;
            if (paymentIntent.MotoMode == true)
            {
                //if it's a moto payment, we need to create the payment intent from
                var servicePM     = new PaymentMethodService();
                var paymentMethod = servicePM.Get(model.StripePaymentIntentId);
                var piCreate      = new PaymentIntentCreateOptions
                {
                    Amount               = (long)paymentIntent.Amount * 100,
                    Currency             = paymentIntent.Currency,
                    Description          = paymentIntent.Description,
                    Confirm              = true,
                    PaymentMethod        = model.StripePaymentIntentId,
                    PaymentMethodOptions = new PaymentIntentPaymentMethodOptionsOptions
                    {
                        Card = new PaymentIntentPaymentMethodOptionsCardOptions
                        {
                            Moto = true
                        }
                    }
                };
                piCreate.Metadata = new Dictionary <string, string>
                {
                    { "TransactionReference", paymentIntent.TransactionReference }
                };
                try
                {
                    stripePI = service.Create(piCreate);
                }
                catch (StripeException ex)
                {
                    stripePI = ex.StripeError.PaymentIntent;
                }

                model.StripePaymentIntentId = stripePI.Id;
            }


            stripePI = stripePI ?? service.Get(model.StripePaymentIntentId);

            if (stripePI.Status == "succeeded" && stripePI.Metadata["TransactionReference"] == model.TransactionReference)
            {
                PaymentService.UpdatePaymentStatus(model.TransactionReference, model.StripePaymentIntentId, PaymentStatus.Succeeded);


                return(Redirect(paymentIntent.ConfirmationPageUrl));
            }

            PaymentService.UpdatePaymentStatus(model.TransactionReference, model.StripePaymentIntentId, PaymentStatus.Failed);

            return(Redirect(paymentIntent.FailurePageUrl));
        }
Exemplo n.º 7
0
        private PaymentIntent GetPaymentIntent(string paymentIntentId)
        {
            StripeConfiguration.ApiKey = ApiSecretKey;
            var           service = new PaymentIntentService();
            PaymentIntent intent  = service.Get(paymentIntentId);

            return(intent);
        }
Exemplo n.º 8
0
        public ActionResult Confirm(PaymentIntentConfirmRequest request)
        {
            var service       = new PaymentIntentService();
            var paymentIntent = service.Get(request.PaymentIntentId);

            var narudzba = db.Rezervacija
                           .Where(x => x.RezervacijaId == request.RezervacijaId)
                           .Include(x => x.RezervacijaIznajmljenaBicikla)
                           .Include(x => x.RezervacijaServis)
                           .FirstOrDefault();
            var narudzba_iznos = (int)narudzba.UkupniIznos * 100;

            if (paymentIntent.Amount == narudzba_iznos && paymentIntent.Status == "succeeded")
            {
                if (narudzba.StanjeRezervacije == StanjeRezervacije.ekanje_uplate)
                {
                    narudzba.StanjeRezervacije = StanjeRezervacije.U_obradi;
                    if (narudzba.DatumUplate is null)
                    {
                        narudzba.DatumUplate = DateTime.Now;
                    }

                    bool IsServisRezervacija = narudzba.RezervacijaServis.Any(),
                         IsTerminRezervacija = narudzba.RezervacijaIznajmljenaBicikla.Any();

                    if (IsServisRezervacija || IsTerminRezervacija || narudzba.NacinPlacanja == "online")
                    {
                        var zaposlenici = db.Zaposlenik.Where(x => x.Korisnik.Aktivan == true).ToList();
                        foreach (var zaposlenik in zaposlenici)
                        {
                            var notifikacija = new Notifikacija
                            {
                                ZaposlenikId = zaposlenik.Id,
                                Rezervacija  = narudzba,
                                DatumVrijeme = DateTime.Now
                            };
                            if (IsServisRezervacija)
                            {
                                notifikacija.Tip = TipNotifikacije.Novi_Servis;
                            }
                            else if (IsTerminRezervacija)
                            {
                                notifikacija.Tip = TipNotifikacije.Novi_Termin;
                            }
                            else
                            {
                                notifikacija.Tip = TipNotifikacije.Nova_Narudzba;
                            }

                            db.Notifikacija.Add(notifikacija);
                        }
                    }
                    db.SaveChanges();
                }
            }

            return(new JsonResult(new { success = true }));
        }
        public IActionResult OffSessionPayment(string customerId, long amount)
        {
            try
            {
                //var amountt=long.Parse(amount);
                var methodOptions = new PaymentMethodListOptions
                {
                    Customer = customerId,
                    Type     = "card",
                };

                var methodService  = new PaymentMethodService();
                var paymentMethods = methodService.List(methodOptions);

                //To get the first payment method
                var payment = paymentMethods.ToList().FirstOrDefault();

                var service = new PaymentIntentService();
                var options = new PaymentIntentCreateOptions
                {
                    Amount        = amount /*ProductAmount*//*1099*/,
                    Currency      = "usd",
                    Customer      = customerId,
                    PaymentMethod = /*PaymentId*//*"card"*/ payment.Id,
                    Confirm       = true,
                    OffSession    = true,
                };
                var paymentIntentt = service.Create(options);

                return(Ok());
                //return View("ButtonsView");
            }

            catch (StripeException e)
            {
                switch (e.StripeError.Error /*.ErrorType*/)
                {
                case "card_error":
                    // Error code will be authentication_required if authentication is needed
                    Console.WriteLine("Error code: " + e.StripeError.Code);
                    var paymentIntentId = e.StripeError.PaymentIntent.Id;
                    var service         = new PaymentIntentService();
                    var paymentIntent   = service.Get(paymentIntentId);

                    Console.WriteLine(paymentIntent.Id);
                    break;

                default:
                    break;
                }
                ////
                return(null);
            }
        }
Exemplo n.º 10
0
        public PaymentResponse GetExistingSession(string id)
        {
            var service = new PaymentIntentService();

            return(new PaymentResponse
            {
                Status = "OK",
                SuccessData = new Dictionary <string, object>()
                {
                    { "paymentIntent", service.Get(id).ToJson() }
                }
            });
        }
        public override ApiResult FetchPaymentStatus(OrderReadOnly order, StripeCheckoutOneTimeSettings settings)
        {
            try
            {
                var secretKey = settings.TestMode ? settings.TestSecretKey : settings.LiveSecretKey;

                ConfigureStripe(secretKey);

                // See if we have a payment intent to work from
                var paymentIntentId = order.Properties["stripePaymentIntentId"];
                if (!string.IsNullOrWhiteSpace(paymentIntentId))
                {
                    var paymentIntentService = new PaymentIntentService();
                    var paymentIntent        = paymentIntentService.Get(paymentIntentId);

                    return(new ApiResult()
                    {
                        TransactionInfo = new TransactionInfoUpdate()
                        {
                            TransactionId = GetTransactionId(paymentIntent),
                            PaymentStatus = GetPaymentStatus(paymentIntent)
                        }
                    });
                }

                // No payment intent, so look for a charge
                var chargeId = order.Properties["stripeChargeId"];
                if (!string.IsNullOrWhiteSpace(chargeId))
                {
                    var chargeService = new ChargeService();
                    var charge        = chargeService.Get(chargeId);

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

            return(ApiResult.Empty);
        }
        public override CallbackResult ProcessCallback(OrderReadOnly order, HttpRequestBase request, StripeCheckoutOneTimeSettings settings)
        {
            // The ProcessCallback method is only intendid to be called via a Stripe Webhook and so
            // it's job is to process the webhook event and finalize / update the order accordingly

            try
            {
                var secretKey            = settings.TestMode ? settings.TestSecretKey : settings.LiveSecretKey;
                var webhookSigningSecret = settings.TestMode ? settings.TestWebhookSigningSecret : settings.LiveWebhookSigningSecret;

                ConfigureStripe(secretKey);

                var stripeEvent = GetWebhookStripeEvent(request, webhookSigningSecret);
                if (stripeEvent != null && stripeEvent.Type == Events.CheckoutSessionCompleted)
                {
                    if (stripeEvent.Data?.Object?.Instance is Session stripeSession)
                    {
                        var paymentIntentService = new PaymentIntentService();
                        var paymentIntent        = paymentIntentService.Get(stripeSession.PaymentIntentId);

                        return(CallbackResult.Ok(new TransactionInfo
                        {
                            TransactionId = GetTransactionId(paymentIntent),
                            AmountAuthorized = AmountFromMinorUnits(paymentIntent.Amount),
                            PaymentStatus = GetPaymentStatus(paymentIntent)
                        },
                                                 new Dictionary <string, string>
                        {
                            { "stripeSessionId", stripeSession.Id },
                            { "stripePaymentIntentId", stripeSession.PaymentIntentId },
                            { "stripeChargeId", GetTransactionId(paymentIntent) },
                            { "stripeCardCountry", paymentIntent.Charges?.Data?.FirstOrDefault()?.PaymentMethodDetails?.Card?.Country }
                        }));
                    }
                }
            }
            catch (Exception ex)
            {
                Vendr.Log.Error <StripeCheckoutOneTimePaymentProvider>(ex, "Stripe - ProcessCallback");
            }

            return(CallbackResult.BadRequest());
        }
        public ActionResult <StripeResult> Get([FromBody] StripeChargeRequest request)
        {
            StripeConfiguration.ApiKey = StripeApiKey;

            StripeResult         result  = new StripeResult();
            PaymentIntentService service = new PaymentIntentService();

            try
            {
                PaymentIntent charge = service.Get(request.Id);
                result.Data    = charge;
                result.Success = true;
            }
            catch (StripeException exception)
            {
                result.Success = false;
                result.Error   = _stripeErrorHandler.ErrorHandler(exception);
            }

            return(result);
        }
        public override int ThreeDSecureCheck(string providerRef, string merchantRef = "", string data1 = "", string data2 = "", string data3 = "")
        {
//	Return
//	   0     : Payment succeeded
//	   1-999 : Payment processed but declined or rejected
// 1001-    : Internal error

            int ret = 10010;

            resultCode = "XX";
            resultMsg  = "Internal failure";
            err        = "";

            try
            {
                ret = 10020;
                StripeConfiguration.ApiKey = Tools.ProviderCredentials("Stripe", "SecretKey");
                ret = 10030;
                var paymentIntentService = new PaymentIntentService();
                ret = 10040;
                //	var paymentIntent          = paymentIntentService.Get(clientSecretId);
                var paymentIntent = paymentIntentService.Get(providerRef);
                ret        = 10050;
                resultCode = paymentIntent.Status;
                ret        = 10060;
                if (resultCode.ToUpper().StartsWith("SUCCE"))
                {
                    resultMsg = "Payment successful";
                    return(0);
                }
                resultMsg = "Payment NOT successful; further action required";
                return(37);
            }
            catch (Exception ex)
            {
                Tools.LogInfo("ThreeDSecureCheck/198", "Ret=" + ret.ToString(), 222, this);
                Tools.LogException("ThreeDSecureCheck/199", "Ret=" + ret.ToString(), ex, this);
            }
            return(ret);
        }
Exemplo n.º 15
0
        public override async Task <OrderReference> GetOrderReferenceAsync(PaymentProviderContext <TSettings> ctx)
        {
            try
            {
                var secretKey            = ctx.Settings.TestMode ? ctx.Settings.TestSecretKey : ctx.Settings.LiveSecretKey;
                var webhookSigningSecret = ctx.Settings.TestMode ? ctx.Settings.TestWebhookSigningSecret : ctx.Settings.LiveWebhookSigningSecret;

                ConfigureStripe(secretKey);

                var stripeEvent = await GetWebhookStripeEventAsync(ctx, webhookSigningSecret);

                if (stripeEvent != null && stripeEvent.Type == Events.CheckoutSessionCompleted)
                {
                    if (stripeEvent.Data?.Object?.Instance is Session stripeSession && !string.IsNullOrWhiteSpace(stripeSession.ClientReferenceId))
                    {
                        return(OrderReference.Parse(stripeSession.ClientReferenceId));
                    }
                }
                else if (stripeEvent != null && stripeEvent.Type == Events.ReviewClosed)
                {
                    if (stripeEvent.Data?.Object?.Instance is Review stripeReview && !string.IsNullOrWhiteSpace(stripeReview.PaymentIntentId))
                    {
                        var paymentIntentService = new PaymentIntentService();
                        var paymentIntent        = paymentIntentService.Get(stripeReview.PaymentIntentId);

                        if (paymentIntent != null && paymentIntent.Metadata.ContainsKey("orderReference"))
                        {
                            return(OrderReference.Parse(paymentIntent.Metadata["orderReference"]));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "Stripe - GetOrderReference");
            }

            return(await base.GetOrderReferenceAsync(ctx));
        }
        public override ApiInfo GetStatus(Order order, IDictionary <string, string> settings)
        {
            try
            {
                order.MustNotBeNull("order");
                settings.MustNotBeNull("settings");
                settings.MustContainKey("mode", "settings");
                settings.MustContainKey(settings["mode"] + "_secret_key", "settings");

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

                ConfigureStripe(apiKey);

                // See if we have a payment intent ID to work from
                var paymentIntentId = order.Properties["stripePaymentIntentId"];
                if (!string.IsNullOrWhiteSpace(paymentIntentId))
                {
                    var paymentIntentService    = new PaymentIntentService();
                    var paymentIntentGetOptions = new PaymentIntentGetOptions();
                    var paymentIntent           = paymentIntentService.Get(paymentIntentId, paymentIntentGetOptions);
                    return(new ApiInfo(GetTransactionId(paymentIntent), GetPaymentState(paymentIntent)));
                }

                // No payment intent, so look for a charge ID
                if (!string.IsNullOrWhiteSpace(order.TransactionInformation.TransactionId))
                {
                    var chargeService = new ChargeService();
                    var charge        = chargeService.Get(order.TransactionInformation.TransactionId);
                    return(new ApiInfo(GetTransactionId(charge), GetPaymentState(charge)));
                }
            }
            catch (Exception exp)
            {
                LoggingService.Instance.Error <Stripe>("Stripe(" + order.OrderNumber + ") - GetStatus", exp);
            }

            return(null);
        }
Exemplo n.º 17
0
        public InvoiceInfo GeneratePayNowLink(
            string customerEmail,
            decimal amountToPay,
            string currency,
            string description = "")
        {
            try
            {
                CustomerCreateOptions customerInfo = new CustomerCreateOptions
                {
                    Email = customerEmail,
                    //PaymentMethod = "card",
                };
                var customerService = new CustomerService();
                var customer        = customerService.Create(customerInfo);

                var invoiceItemOption = new InvoiceItemCreateOptions
                {
                    Customer = customer.Id,
                    Amount   = Convert.ToInt32(amountToPay * 100),
                    Currency = currency,
                };
                var invoiceItemService = new InvoiceItemService();
                var invoiceItem        = invoiceItemService.Create(invoiceItemOption);

                var invoiceOptions = new InvoiceCreateOptions
                {
                    Customer         = customer.Id,
                    CollectionMethod = "send_invoice",
                    DaysUntilDue     = 30,
                    Description      = description
                };

                var service = new InvoiceService();
                var invoice = service.Create(invoiceOptions);

                invoice = service.FinalizeInvoice(invoice.Id);

                try
                {
                    var paymentIntentService = new PaymentIntentService();

                    var paymentIntent = paymentIntentService.Get(invoice.PaymentIntentId);
                    var paymentIntentUpdateOptions = new PaymentIntentUpdateOptions
                    {
                        Description = description
                    };
                    paymentIntentService.Update(paymentIntent.Id, paymentIntentUpdateOptions);
                }
                catch (Exception)
                {
                    //continue
                }

                var result = new InvoiceInfo
                {
                    Url = invoice.HostedInvoiceUrl,
                    Id  = invoice.Id
                };
                return(result);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(null);
            }
        }
        public override async Task <CallbackResult> ProcessCallbackAsync(PaymentProviderContext <StripeCheckoutSettings> ctx)
        {
            // The ProcessCallback method is only intendid to be called via a Stripe Webhook and so
            // it's job is to process the webhook event and finalize / update the ctx.Order accordingly

            try
            {
                var secretKey            = ctx.Settings.TestMode ? ctx.Settings.TestSecretKey : ctx.Settings.LiveSecretKey;
                var webhookSigningSecret = ctx.Settings.TestMode ? ctx.Settings.TestWebhookSigningSecret : ctx.Settings.LiveWebhookSigningSecret;

                ConfigureStripe(secretKey);

                var stripeEvent = await GetWebhookStripeEventAsync(ctx, webhookSigningSecret);

                if (stripeEvent != null && stripeEvent.Type == Events.CheckoutSessionCompleted)
                {
                    if (stripeEvent.Data?.Object?.Instance is Session stripeSession)
                    {
                        if (stripeSession.Mode == "payment")
                        {
                            var paymentIntentService = new PaymentIntentService();
                            var paymentIntent        = await paymentIntentService.GetAsync(stripeSession.PaymentIntentId, new PaymentIntentGetOptions
                            {
                                Expand = new List <string>(new[] {
                                    "review"
                                })
                            });

                            return(CallbackResult.Ok(new TransactionInfo
                            {
                                TransactionId = GetTransactionId(paymentIntent),
                                AmountAuthorized = AmountFromMinorUnits(paymentIntent.Amount),
                                PaymentStatus = GetPaymentStatus(paymentIntent)
                            },
                                                     new Dictionary <string, string>
                            {
                                { "stripeSessionId", stripeSession.Id },
                                { "stripeCustomerId", stripeSession.CustomerId },
                                { "stripePaymentIntentId", stripeSession.PaymentIntentId },
                                { "stripeSubscriptionId", stripeSession.SubscriptionId },
                                { "stripeChargeId", GetTransactionId(paymentIntent) },
                                { "stripeCardCountry", paymentIntent.Charges?.Data?.FirstOrDefault()?.PaymentMethodDetails?.Card?.Country }
                            }));
                        }
                        else if (stripeSession.Mode == "subscription")
                        {
                            var subscriptionService = new SubscriptionService();
                            var subscription        = await subscriptionService.GetAsync(stripeSession.SubscriptionId, new SubscriptionGetOptions {
                                Expand = new List <string>(new[] {
                                    "latest_invoice",
                                    "latest_invoice.charge",
                                    "latest_invoice.charge.review",
                                    "latest_invoice.payment_intent",
                                    "latest_invoice.payment_intent.review"
                                })
                            });

                            var invoice = subscription.LatestInvoice;

                            return(CallbackResult.Ok(new TransactionInfo
                            {
                                TransactionId = GetTransactionId(invoice),
                                AmountAuthorized = AmountFromMinorUnits(invoice.PaymentIntent.Amount),
                                PaymentStatus = GetPaymentStatus(invoice)
                            },
                                                     new Dictionary <string, string>
                            {
                                { "stripeSessionId", stripeSession.Id },
                                { "stripeCustomerId", stripeSession.CustomerId },
                                { "stripePaymentIntentId", invoice.PaymentIntentId },
                                { "stripeSubscriptionId", stripeSession.SubscriptionId },
                                { "stripeChargeId", invoice.ChargeId },
                                { "stripeCardCountry", invoice.Charge?.PaymentMethodDetails?.Card?.Country }
                            }));
                        }
                    }
                    else if (stripeEvent != null && stripeEvent.Type == Events.ReviewClosed)
                    {
                        if (stripeEvent.Data?.Object?.Instance is Review stripeReview && !string.IsNullOrWhiteSpace(stripeReview.PaymentIntentId))
                        {
                            var paymentIntentService = new PaymentIntentService();
                            var paymentIntent        = paymentIntentService.Get(stripeReview.PaymentIntentId, new PaymentIntentGetOptions
                            {
                                Expand = new List <string>(new[] {
                                    "review"
                                })
                            });

                            return(CallbackResult.Ok(new TransactionInfo
                            {
                                TransactionId = GetTransactionId(paymentIntent),
                                AmountAuthorized = AmountFromMinorUnits(paymentIntent.Amount),
                                PaymentStatus = GetPaymentStatus(paymentIntent)
                            }));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "Stripe - ProcessCallback");
            }

            return(CallbackResult.BadRequest());
        }
        public async Task <IActionResult> Webhook()
        {
            var   json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();
            Event stripeEvent;

            try
            {
                stripeEvent = EventUtility.ConstructEvent(
                    json,
                    Request.Headers["Stripe-Signature"],
                    this.options.Value.WebhookSecret
                    );
                Console.WriteLine($"Webhook notification with type: {stripeEvent.Type} found for {stripeEvent.Id}");
            }
            catch (Exception e)
            {
                Console.WriteLine($"Something failed {e}");
                return(BadRequest());
            }

            if (stripeEvent.Type == "invoice.payment_succeeded")
            {
                var invoice = stripeEvent.Data.Object as Invoice;

                if (invoice.BillingReason == "subscription_create")
                {
                    // The subscription automatically activates after successful payment
                    // Set the payment method used to pay the first invoice
                    // as the default payment method for that subscription

                    // Retrieve the payment intent used to pay the subscription
                    var service       = new PaymentIntentService();
                    var paymentIntent = service.Get(invoice.PaymentIntentId);

                    // Set the default payment method
                    var options = new SubscriptionUpdateOptions
                    {
                        DefaultPaymentMethod = paymentIntent.PaymentMethodId,
                    };
                    var subscriptionService = new SubscriptionService();
                    subscriptionService.Update(invoice.SubscriptionId, options);

                    Console.WriteLine($"Default payment method set for subscription: {paymentIntent.PaymentMethodId}");
                }
                Console.WriteLine($"Payment succeeded for invoice: {stripeEvent.Id}");
            }

            if (stripeEvent.Type == "invoice.paid")
            {
                // Used to provision services after the trial has ended.
                // The status of the invoice will show up as paid. Store the status in your
                // database to reference when a user accesses your service to avoid hitting rate
                // limits.
            }
            if (stripeEvent.Type == "invoice.payment_failed")
            {
                // If the payment fails or the customer does not have a valid payment method,
                // an invoice.payment_failed event is sent, the subscription becomes past_due.
                // Use this webhook to notify your user that their payment has
                // failed and to retrieve new card details.
            }
            if (stripeEvent.Type == "invoice.finalized")
            {
                // If you want to manually send out invoices to your customers
                // or store them locally to reference to avoid hitting Stripe rate limits.
            }
            if (stripeEvent.Type == "customer.subscription.deleted")
            {
                // handle subscription cancelled automatically based
                // upon your subscription settings. Or if the user cancels it.
            }
            if (stripeEvent.Type == "customer.subscription.trial_will_end")
            {
                // Send notification to your user that the trial will end
            }

            return(Ok());
        }
Exemplo n.º 20
0
        public string SendInvoice(
            string customerEmail,
            decimal amountToPay,
            string currency,
            string description = "",
            bool sendInvoice   = true)
        {
            try
            {
                CustomerCreateOptions customerInfo = new CustomerCreateOptions
                {
                    Email = customerEmail,
                    //PaymentMethod = "card",
                };
                var customerService = new CustomerService();
                var customer        = customerService.Create(customerInfo);

                var invoiceItemOption = new InvoiceItemCreateOptions
                {
                    Customer = customer.Id,
                    Amount   = Convert.ToInt32(amountToPay * 100),
                    Currency = currency,
                };
                var invoiceItemService = new InvoiceItemService();
                var invoiceItem        = invoiceItemService.Create(invoiceItemOption);

                var invoiceOptions = new InvoiceCreateOptions
                {
                    Customer         = customer.Id,
                    CollectionMethod = "send_invoice",
                    DaysUntilDue     = 30,
                    Description      = description,
                    AutoAdvance      = true
                };

                var service = new InvoiceService();
                var invoice = service.Create(invoiceOptions);
                invoice = service.FinalizeInvoice(invoice.Id);

                try
                {
                    var paymentIntentService = new PaymentIntentService();

                    var paymentIntent = paymentIntentService.Get(invoice.PaymentIntentId);
                    var paymentIntentUpdateOptions = new PaymentIntentUpdateOptions
                    {
                        Description = description
                    };
                    paymentIntentService.Update(paymentIntent.Id, paymentIntentUpdateOptions);
                }
                catch (Exception)
                {
                    //continue
                }

                if (sendInvoice)
                {
                    invoice = service.SendInvoice(invoice.Id);
                }

                return(invoice.Id);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(null);
            }
        }
Exemplo n.º 21
0
        public async System.Threading.Tasks.Task <ActionResult> statusPayment(string id)
        {
            try
            {
                var service = new PaymentIntentService();
                var intent  = service.Get(id);
                if (intent.Status.Contains("succeeded"))
                {
                    int iid         = int.Parse(intent.Metadata["invoiceID"]);
                    var transaction = new Models.Database.Transaction
                    {
                        invoiceid       = iid,
                        paymentmethodid = 1,
                        reference       = id,
                        total           = decimal.Parse((Convert.ToDecimal(intent.Amount) / 100).ToString(".00")),
                        transdate       = DateTime.Now
                    };
                    db.Transactions.Add(transaction);
                    db.SaveChanges();

                    var invoice = db.Invoices.Find(iid);
                    //invoice.totalunpaid -= decimal.Parse((intent.Amount / 100).ToString(".00"));
                    //invoice.status = "Paid";
                    //db.Entry(invoice).State = System.Data.Entity.EntityState.Modified;
                    //db.SaveChanges();

                    //var job = db.Jobs.Find(invoice.jobid);
                    //job.jobstatusid = 1;
                    //db.SaveChanges();

                    //Remove Data from Firebase (Quoted Items)
                    var userTrans = db.Transactions.Where(x => x.Invoice.jobid == invoice.jobid);
                    if (userTrans.Count() == 1)
                    {
                        var userInvoice = userTrans.FirstOrDefault().Invoice.Job;
                        var package     = userInvoice.Package;
                        var userid      = userInvoice.User.id;
                        var chatkey     = package.Studio.ChatKeys.FirstOrDefault(x => x.UserID == userid).ChatKeyID;

                        FirestoreDb firestore = FirestoreDb.Create("photogw2");

                        var collection = firestore.Collection("Quotation");
                        var query      = collection.WhereEqualTo("ChatKey", chatkey);
                        var snapshot   = await query.GetSnapshotAsync();

                        var deserializedDataQuoteAll = snapshot.FirstOrDefault().ConvertTo <QuotationModel>();

                        var chat = db.ChatKeys.FirstOrDefault(x => x.ChatKeyID == deserializedDataQuoteAll.ChatKey);
                        var deserializedDataSel = deserializedDataQuoteAll.Packages.FirstOrDefault(x => x.Package.Id == package.id);

                        deserializedDataQuoteAll.Packages.Remove(deserializedDataSel);

                        await collection.Document(snapshot.FirstOrDefault().Id).SetAsync(deserializedDataQuoteAll);
                    }

                    return(View("success", db.Transactions.FirstOrDefault(x => x.invoiceid == iid)));
                }
                else
                {
                    return(View("cancel"));
                }
            }
            catch (Exception e)
            {
                return(RedirectToAction("Error500", "Home", new { errormsg = e.Message }));
            }
        }
Exemplo n.º 22
0
        protected async Task <StripeWebhookEvent> GetWebhookStripeEventAsync(PaymentProviderContext <TSettings> ctx, string webhookSigningSecret)
        {
            StripeWebhookEvent stripeEvent = null;

            if (ctx.AdditionalData.ContainsKey("Vendr_StripeEvent"))
            {
                stripeEvent = (StripeWebhookEvent)ctx.AdditionalData["Vendr_StripeEvent"];
            }
            else
            {
                try
                {
                    var json = await ctx.Request.Content.ReadAsStringAsync();

                    var stripeSignature = ctx.Request.Headers.GetValues("Stripe-Signature").FirstOrDefault();

                    // Just validate the webhook signature
                    EventUtility.ValidateSignature(json, stripeSignature, webhookSigningSecret);

                    // Parse the event ourselves to our custom webhook event model
                    // as it only captures minimal object information.
                    stripeEvent = JsonConvert.DeserializeObject <StripeWebhookEvent>(json);

                    // We manually fetch the event object type ourself as it means it will be fetched
                    // using the same API version as the payment providers is coded against.
                    // NB: Only supports a number of object types we are likely to be interested in.
                    if (stripeEvent?.Data?.Object != null)
                    {
                        switch (stripeEvent.Data.Object.Type)
                        {
                        case "checkout.session":
                            var sessionService = new SessionService();
                            stripeEvent.Data.Object.Instance = sessionService.Get(stripeEvent.Data.Object.Id);
                            break;

                        case "charge":
                            var chargeService = new ChargeService();
                            stripeEvent.Data.Object.Instance = chargeService.Get(stripeEvent.Data.Object.Id);
                            break;

                        case "payment_intent":
                            var paymentIntentService = new PaymentIntentService();
                            stripeEvent.Data.Object.Instance = paymentIntentService.Get(stripeEvent.Data.Object.Id);
                            break;

                        case "subscription":
                            var subscriptionService = new SubscriptionService();
                            stripeEvent.Data.Object.Instance = subscriptionService.Get(stripeEvent.Data.Object.Id);
                            break;

                        case "invoice":
                            var invoiceService = new InvoiceService();
                            stripeEvent.Data.Object.Instance = invoiceService.Get(stripeEvent.Data.Object.Id);
                            break;

                        case "review":
                            var reviewService = new ReviewService();
                            stripeEvent.Data.Object.Instance = reviewService.Get(stripeEvent.Data.Object.Id);
                            break;
                        }
                    }

                    ctx.AdditionalData.Add("Vendr_StripeEvent", stripeEvent);
                }
                catch (Exception ex)
                {
                    _logger.Error(ex, "Stripe - GetWebhookStripeEvent");
                }
            }

            return(stripeEvent);
        }
        async void placeOrder(object sender, System.EventArgs e)
        {
            var request = new HttpRequestMessage();

            request.RequestUri = new Uri("http://10.0.2.2:5000/api/v1/payment");

            request.Method = HttpMethod.Get;
            var client = new HttpClient();
            MultipartFormDataContent requestContent = new MultipartFormDataContent();
            StringContent            amountContent  = new StringContent("9923", Encoding.UTF8);

            requestContent.Add(amountContent, "amount");
            request.Content = requestContent;


            HttpResponseMessage response = await client.SendAsync(request);

            StripeConfiguration.ApiKey = "pk_test_j5YImiDFgybfafp8HuEkn6Ou00JtFKI0s9";

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                HttpContent content        = response.Content;
                var         responseString = await content.ReadAsStringAsync();

                var messageObj    = JsonConvert.DeserializeObject <message>(responseString);
                var client_secret = messageObj.client_secret;

                var service    = new PaymentIntentService();
                var getOptions = new PaymentIntentGetOptions
                {
                    ClientSecret = client_secret
                };
                PaymentIntent paymentIntent = service.Get(messageObj.id, getOptions);

                //var creditCardOptions = new CreditCardOptions
                //{
                //    Number = "4000 0000 0000 9995",
                //    Cvc = "333",
                //    ExpMonth = 02,
                //    ExpYear = 24,

                //};

                var paymentMethodCardCreateOption = new PaymentMethodCardCreateOptions {
                    //Insufficiant fund
                    //Number = "4000000000009995",
                    //Payment Succeed
                    //Number = "4242424242424242",
                    //Payment Require Authentication
                    //Number = "4000002500003155",
                    Number   = CreditCardNumber.Text,
                    Cvc      = CVC.Text,
                    ExpMonth = long.Parse(ExpMonth.Text),
                    ExpYear  = long.Parse(ExpYear.Text),
                };

                //var paymentMethodDataOption = new PaymentIntentPaymentMethodDataOptions
                //{
                //    Card = paymentMethodCardCreateOption,
                //    Type = "card",

                //};
                List <String> methodTypes = new List <String>();
                methodTypes.Add("pm_card_visa");
                var confirmOptions = new PaymentIntentConfirmOptions
                {
                    //PaymentMethod = "pm_card_visa",
                    PaymentMethodData = paymentMethodDataOption,

                    ClientSecret = client_secret,
                };
                try
                {
                    var status = service.Confirm(messageObj.id, confirmOptions);
                    if (status.Status == "succeeded")
                    {
                        await DisplayAlert("Request Sent!", "Our customer service will reach out to you in 3-5 bussiness days", "OK");
                    }
                    else
                    {
                        await DisplayAlert("Failed", "Please try another card", "OK");
                    }
                }
                catch (Exception)
                {
                    await DisplayAlert("Failed", "Please try another card", "OK");
                }


                //Console.WriteLine(status.Status);
            }
        }
        protected StripeWebhookEvent GetWebhookStripeEvent(HttpRequestBase request, string webhookSigningSecret)
        {
            StripeWebhookEvent stripeEvent = null;

            if (HttpContext.Current.Items["Vendr_StripeEvent"] != null)
            {
                stripeEvent = (StripeWebhookEvent)HttpContext.Current.Items["Vendr_StripeEvent"];
            }
            else
            {
                try
                {
                    if (request.InputStream.CanSeek)
                    {
                        request.InputStream.Seek(0, SeekOrigin.Begin);
                    }

                    using (var reader = new StreamReader(request.InputStream))
                    {
                        var json = reader.ReadToEnd();

                        // Just validate the webhook signature
                        EventUtility.ValidateSignature(json, request.Headers["Stripe-Signature"], webhookSigningSecret);

                        // Parse the event ourselves to our custom webhook event model
                        // as it only captures minimal object information.
                        stripeEvent = JsonConvert.DeserializeObject <StripeWebhookEvent>(json);

                        // We manually fetch the event object type ourself as it means it will be fetched
                        // using the same API version as the payment providers is coded against.
                        // NB: Only supports a number of object types we are likely to be interested in.
                        if (stripeEvent?.Data?.Object != null)
                        {
                            switch (stripeEvent.Data.Object.Type)
                            {
                            case "checkout.session":
                                var sessionService = new SessionService();
                                stripeEvent.Data.Object.Instance = sessionService.Get(stripeEvent.Data.Object.Id);
                                break;

                            case "charge":
                                var chargeService = new ChargeService();
                                stripeEvent.Data.Object.Instance = chargeService.Get(stripeEvent.Data.Object.Id);
                                break;

                            case "payment_intent":
                                var paymentIntentService = new PaymentIntentService();
                                stripeEvent.Data.Object.Instance = paymentIntentService.Get(stripeEvent.Data.Object.Id);
                                break;

                            case "subscription":
                                var subscriptionService = new SubscriptionService();
                                stripeEvent.Data.Object.Instance = subscriptionService.Get(stripeEvent.Data.Object.Id);
                                break;

                            case "invoice":
                                var invoiceService = new InvoiceService();
                                stripeEvent.Data.Object.Instance = invoiceService.Get(stripeEvent.Data.Object.Id);
                                break;
                            }
                        }

                        HttpContext.Current.Items["Vendr_StripeEvent"] = stripeEvent;
                    }
                }
                catch (Exception ex)
                {
                    Vendr.Log.Error <StripePaymentProviderBase <TSettings> >(ex, "Stripe - GetWebhookStripeEvent");
                }
            }

            return(stripeEvent);
        }
Exemplo n.º 25
0
        public PaymentIntent GetPaymentIntentById(string id)
        {
            var paymentIntentService = new PaymentIntentService();

            return(paymentIntentService.Get(id));
        }