Exemplo n.º 1
0
        public async Task <ActionResult> StripeCallbackAsync()
        {
            Event stripeEvent;

            try
            {
                stripeEvent = EventUtility.ConstructEvent(
                    await new StreamReader(HttpContext.Request.Body).ReadToEndAsync(),
                    Request.Headers["Stripe-Signature"],
                    _stripeOptions.CurrentValue.WebhookSecret,
                    throwOnApiVersionMismatch: false);
            }
            catch (StripeException)
            {
                // event construction failed, so request wasn't valid
                return(ResultUtilities.BadRequest("You're not stripe, are you?"));
            }

            switch (stripeEvent.Type)
            {
            case Events.CheckoutSessionCompleted when stripeEvent.Data.Object is Session session:
                await _stripe.HandleSupporterCheckoutCompletedAsync(session);

                break;

            default:
                return(ResultUtilities.BadRequest($"Stripe event {stripeEvent.Type} should not be received by this server."));
            }

            return(Ok());
        }
Exemplo n.º 2
0
        public async Task <IActionResult> WebHooks()
        {
            var json = new StreamReader(HttpContext.Request.Body).ReadToEnd();

            try
            {
                var stripeEvent = EventUtility.ConstructEvent(json, Request.Headers["Stripe-Signature"], _stripeConfiguration.WebhookSecret);

                if (stripeEvent.Type == Events.InvoicePaymentSucceeded)
                {
                    await HandleSubscriptionCyclePaymentAsync(stripeEvent);
                }

                if (stripeEvent.Type == Events.CheckoutSessionCompleted)
                {
                    await HandleCheckoutSessionCompletedAsync(stripeEvent);
                }

                // Other WebHook events can be handled here.

                return(Ok());
            }
            catch (ApplicationException exception)
            {
                Logger.Error(exception.Message, exception);
                return(BadRequest());
            }
            catch (StripeException exception)
            {
                Logger.Error(exception.Message, exception);
                return(BadRequest());
            }
        }
Exemplo n.º 3
0
        public async Task <ActionResult> StripeWebhook()
        {
            var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();

            var stripeEvent = EventUtility.ConstructEvent(json, Request.Headers["Stripe-Signature"],
                                                          _whSecret);

            PaymentIntent intent;
            Order         order;

            switch (stripeEvent.Type)
            {
            case "payment_intent.suceeded":
                intent = (PaymentIntent)stripeEvent.Data.Object;
                _logger.LogInformation("Payment Succeeded: ", intent.Id);
                order = await _paymentService.UpdateOrderPaymentSucceeded(intent.Id);

                _logger.LogInformation("Order updated to payment receiver: ", order.Id);
                break;

            case "payment_intent.payment_failed":
                intent = (PaymentIntent)stripeEvent.Data.Object;
                _logger.LogInformation("Payment Failed: ", intent.Id);
                order = await _paymentService.UpdateOrderPaymentFailed(intent.Id);

                _logger.LogInformation("Payment failed: ", order.Id);
                break;
            }

            return(new EmptyResult());
        }
Exemplo n.º 4
0
        public async Task <ActionResult> StripeWebhook()
        {
            var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();

            // Parses a JSON string from a Stripe webhook into a Stripe.Event object while verifying
            // the webhook's signature. Ignore the version check
            var stripeEvent = EventUtility.ConstructEvent(json, Request.Headers["Stripe-Signature"],
                                                          WhSecret, 300, false);

            PaymentIntent intent;
            Order         order;

            switch (stripeEvent.Type)
            {
            case "payment_intent.succeeded":
                intent = (PaymentIntent)stripeEvent.Data.Object;
                _logger.LogInformation("Payment Succeded: ", intent.Id);
                order = await _paymentService.UpdateOrderPaymentSucceeded(intent.Id);

                _logger.LogInformation("Order updated to payment received", order.Id);
                break;

            case "payment_intent.payment_failed":
                intent = (PaymentIntent)stripeEvent.Data.Object;
                _logger.LogInformation("Payment Failed: ", intent.Id);
                order = await _paymentService.UpdateOrderPaymentFailed(intent.Id);

                _logger.LogInformation("Order updated to payment failed", order.Id);
                break;
            }

            //Confirms to Stripe that we have received the event or else Stripe keeps trying for days
            return(new EmptyResult());
        }
Exemplo n.º 5
0
        public async Task <ActionResult> StripeWebHook()
        {
            var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();

            var stripeEvent = EventUtility.ConstructEvent(json, Request.Headers["Stripe-Signature"], _configuration["StripeSettings:WhSecret"]);

            PaymentIntent intent = null;
            Order         order  = null;

            switch (stripeEvent.Type)
            {
            case "payment_intent.succeeded":
                intent = (PaymentIntent)stripeEvent.Data.Object;
                _logger.LogInformation("Paymnet succeed: " + intent.Id);
                //TODO: Update Order Status
                order = await _paymentService.UpdatePaymentIntentSucceeded(intent.Id);

                _logger.LogInformation("Payment Review with Order: " + order.Id);
                break;

            case "payment_intent.payment_failed":
                intent = (PaymentIntent)stripeEvent.Data.Object;
                _logger.LogInformation("Paymnet failed: " + intent.Id);
                //TODO: Update Order Status
                order = await _paymentService.UpdatePaymentIntentFailed(intent.Id);

                _logger.LogInformation("Payment Failed with Order: " + order.Id);
                break;
            }

            return(new EmptyResult());
        }
Exemplo n.º 6
0
        /// <summary>
        ///  localhost:8000/Webhooks.ashx
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            var endpointSecret = "whsec_CEnfjmYibVGzKb66XdWdlSw06T8CONsz";
            var json           = new StreamReader(context.Request.InputStream).ReadToEnd();

            try
            {
                var stripeEvent = EventUtility.ConstructEvent(
                    json,
                    context.Request.Headers["Stripe-Signature"],
                    endpointSecret
                    );

                switch (stripeEvent.Type)
                {
                case Events.PaymentIntentSucceeded:
                    // look up the payment in the database and update it's state
                    // fulfill order
                    // send a customer email
                    //
                    var paymentIntent = stripeEvent.Data.Object as PaymentIntent;
                    Console.WriteLine($"Payment Succeeded {paymentIntent.Id} for ${paymentIntent.Amount}");
                    break;

                default:
                    Console.WriteLine($"Got event {stripeEvent.Type}");
                    break;
                }
            }
            catch (StripeException e)
            {
                Console.WriteLine(e);
                throw e;
            }
        }
        public async Task <IActionResult> StripeWebhook()
        {
            var WhSecret = _config["StripeSettings:WebhookSecret"];

            var json        = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();
            var stripeEvent = EventUtility.ConstructEvent(json, Request.Headers["Stripe-Signature"], WhSecret);

            Stripe.PaymentIntent intent;

            switch (stripeEvent.Type)
            {
            case "payment_intent.succeeded":
                intent = (Stripe.PaymentIntent)stripeEvent.Data.Object;
                await service.UpdateOrderPaymentSucceeded(intent.Id);

                break;

            case "payment_intent.payment_failed":
                intent = (Stripe.PaymentIntent)stripeEvent.Data.Object;
                service.UpdateOrderPaymentFailed(intent.Id);
                break;
            }

            return(new EmptyResult());
        }
Exemplo n.º 8
0
        public async Task <IHttpActionResult> Webhook(HttpRequestMessage request)
        {
            var json = await request.Content.ReadAsStringAsync();

            try
            {
                var stripeEvent = EventUtility.ConstructEvent(json, request.Headers.GetValues("Stripe-Signature").FirstOrDefault(), Config.StripeWebhookSecretKey);

                if (stripeEvent.Type == Events.ChargeSucceeded || stripeEvent.Type == Events.ChargeFailed)
                {
                    var charge = stripeEvent.Data.Object as Charge;
                    InsertStripeEvent(charge.CustomerId, json);
                }

                var subscriptionEvents = new string[] {
                    Events.CustomerSubscriptionCreated,
                    Events.CustomerSubscriptionDeleted,
                    Events.CustomerSubscriptionUpdated
                };
                if (subscriptionEvents.Contains(stripeEvent.Type))
                {
                    var subscription = stripeEvent.Data.Object as Subscription;
                    InsertStripeEvent(subscription.CustomerId, json);
                }

                return(Ok());
            }
            catch (StripeException e)
            {
                return(BadRequest());
            }
        }
Exemplo n.º 9
0
// Webhook вызовет наш api с информацией об успешной оплате
        public async Task <ActionResult> StripeWebHook()
        {
            var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();

// проверяем, действительно ли запрос от полосы
            var stripeEvent = EventUtility.ConstructEvent(json, Request.Headers["Stripe-Signature"], _whSecret);

            PaymentIntent intent;
            Order         order;

            switch (stripeEvent.Type)
            {
            case "payment_intent.succeeded":
                intent = (PaymentIntent)stripeEvent.Data.Object;
                _logger.LogInformation("Payment succeeded: ", intent.Id);
                order = await _paymentService.UpdateOrderPaymentOrderSucceeded(intent.Id);

                _logger.LogInformation("Order updated to payment received: ", order.Id);
                break;

            case "payment_intent.payment_failed":
                intent = (PaymentIntent)stripeEvent.Data.Object;
                _logger.LogInformation("Payment Failed: ", intent.Id);
                order = await _paymentService.UpdateOrderPaymentOrderFailed(intent.Id);

                _logger.LogInformation("Payment failed: ", order.Id);
                break;
            }
// Нам нужно подтвердить полосе, что мы получили их событие.
            return(new EmptyResult());
        }
Exemplo n.º 10
0
        public void RejectMessageWithUnicode()
        {
            var exception = Assert.Throws <StripeException>(() =>
                                                            EventUtility.ConstructEvent(this.json + "\ud802", this.signature, this.secret));

            Assert.Equal("The webhook cannot be processed because the signature cannot be safely calculated.", exception.Message);
        }
Exemplo n.º 11
0
        public async Task <ActionResult> StripeWebHook()
        {
            var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();

            var stripeEvent = EventUtility.ConstructEvent(json, Request.Headers["Stripe-Signature"], WhSecret, throwOnApiVersionMismatch: false);

            PaymentIntent intent;

            Order order;


            switch (stripeEvent.Type)
            {
            case "payment_intent.succeeded":
                intent = (PaymentIntent)stripeEvent.Data.Object;
                _logger.LogInformation("Payment succeeded", intent.Id);
                order = await _paymentService.UpdateOrderPaymentSucceeded(intent.Id);

                _logger.LogInformation("Order updated to payment received", order.Id);
                break;

            case "payment_intent.payment_failed":
                intent = (PaymentIntent)stripeEvent.Data.Object;
                _logger.LogInformation("Payment Failed", intent.Id);
                // todo: update order with new status
                order = await _paymentService.UpdateOrderPaymentFailed(intent.Id);

                _logger.LogInformation("Order updated to payment failed", order.Id);
                break;
            }


            // live mode if does not get back from our API, return here to prevent sending by Stripe
            return(new EmptyResult());
        }
Exemplo n.º 12
0
        public async Task <ActionResult> StripeWebhook()
        {
            var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();

            // to confirm that the payment from Stripe was successful
            var stripeEvent = EventUtility.ConstructEvent(json, Request.Headers["Stripe-Signature"], _whSecret);

            PaymentIntent intent;
            Order         order;

            switch (stripeEvent.Type)
            {
            case "payment_intent.succeeded":
                intent = (PaymentIntent)stripeEvent.Data.Object;
                _logger.LogInformation("Payment Succeeded: ", intent.Id);
                // update order with new status
                order = await _paymentService.UpdateOrderPaymentSucceeded(intent.Id);

                _logger.LogInformation("Order updated to payment received: ", order.Id);
                break;

            case "payment_intent.payment_failed":
                intent = (PaymentIntent)stripeEvent.Data.Object;
                _logger.LogInformation("Payment Failed: ", intent.Id);
                // update order
                order = await _paymentService.UpdateOrderPaymentFailed(intent.Id);

                _logger.LogInformation("Payment Failed: ", order.Id);
                break;
            }
            // Stripe needs this for result: (otherwise it keeps sending the event)
            return(new EmptyResult());
        }
Exemplo n.º 13
0
    public async Task <IActionResult> PostAsync()
    {
        string json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();

        using (_logger.BeginScope(new ExceptionlessState().SetHttpContext(HttpContext).Property("event", json))) {
            if (String.IsNullOrEmpty(json))
            {
                _logger.LogWarning("Unable to get json of incoming event.");
                return(BadRequest());
            }

            Stripe.Event stripeEvent;
            try {
                stripeEvent = EventUtility.ConstructEvent(json, Request.Headers["Stripe-Signature"], _stripeOptions.StripeWebHookSigningSecret, throwOnApiVersionMismatch: false);
            }
            catch (Exception ex) {
                _logger.LogError(ex, "Unable to parse incoming event with {Signature}: {Message}", Request.Headers["Stripe-Signature"], ex.Message);
                return(BadRequest());
            }

            if (stripeEvent == null)
            {
                _logger.LogWarning("Null stripe event.");
                return(BadRequest());
            }

            await _stripeEventHandler.HandleEventAsync(stripeEvent);

            return(Ok());
        }
    }
Exemplo n.º 14
0
        // with this method we need to read what is coming in from stripe to this endpoint
        public async Task <ActionResult> StripeWebhook()
        {
            var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();

            // this is the part where we are confirming the payment from the client and web hook needs to be available anonymously
            // ( without [Authorize] atribute above method )
            // and we want to make sure that is definitely receiving this from Stripe before we move forward
            var stripeEvent = EventUtility.ConstructEvent(json, Request.Headers["Stripe-Signature"], WhSecret);

            PaymentIntent intent;
            Order         order;

            switch (stripeEvent.Type)
            {
            case "payment_intent.succeeded":
                intent = (PaymentIntent)stripeEvent.Data.Object;
                _logger.LogInformation("Payment Succeeded: ", intent.Id);
                // update order with new status succeeded
                order = await _paymentService.UpdateOrderPaymentSucceeded(intent.Id);

                _logger.LogInformation("Order updated to payment received: ", order.Id);
                break;

            case "payment_intent.payment_failed":
                intent = (PaymentIntent)stripeEvent.Data.Object;
                _logger.LogInformation("Payment Failed: ", intent.Id);
                // update order with new status failed
                order = await _paymentService.UpdateOrderPaymentFailed(intent.Id);

                _logger.LogInformation("Payment Failed: ", order.Id);
                break;
            }

            return(new EmptyResult());
        }
Exemplo n.º 15
0
        public async Task <IActionResult> ConnectWebHook()
        {
            var   json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();
            Event stripeEvent;

            try
            {
                stripeEvent = EventUtility.ConstructEvent(
                    json,
                    Request.Headers["Stripe-Signature"],
                    Configuration.GetValue <string>("StripeCredentials: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 == Events.AccountUpdated)
            {
                Account       account = stripeEvent.Data.Object as Account;
                StripeService service = new StripeService(_userRepository, Configuration);
                if (account.ChargesEnabled)
                {
                    await service.UpdateStripeConnected(account.Id);
                }
            }
            return(Ok());
        }
Exemplo n.º 16
0
        public async Task <IActionResult> Index()
        {
            var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();

            try
            {
                var stripeEvent = EventUtility.ConstructEvent(json, Request.Headers["Stripe-Signature"], endpointSecret);

                // Handle the event
                if (stripeEvent.Type == Events.PaymentIntentSucceeded)
                {
                    var paymentIntent = stripeEvent.Data.Object as PaymentIntent;
                    Console.WriteLine(paymentIntent);
                }
                else if (stripeEvent.Type == Events.PaymentMethodAttached)
                {
                    var paymentMethod = stripeEvent.Data.Object as PaymentMethod;
                    Console.WriteLine(paymentMethod);
                }
                // ... handle other event types
                else
                {
                    // Unexpected event type
                    return(BadRequest());
                }

                return(Ok());
            }
            catch (StripeException e)
            {
                return(BadRequest());
            }
        }
Exemplo n.º 17
0
        public async Task <ActionResult> StripeWebhook()
        {
            //        _logger.LogInformation("*********************in the stripe webhook action ");

            var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();

            var whSecret = _config.GetValue <string>("Stripe:WhSecret");

            var stripeEvent = EventUtility.ConstructEvent(json, Request.Headers["Stripe-Signature"], whSecret);

            PaymentIntent intent;

            switch (stripeEvent.Type)
            {
            case "payment_intent.succeeded":
                intent = (PaymentIntent)stripeEvent.Data.Object;
                var holiday = await _paymentService.PaymentSuccessful(intent);

                //                  _logger.LogInformation("************Holiday created id#", holiday.Id);
                break;

            case "payment_intent.payment_failed":
                intent = (PaymentIntent)stripeEvent.Data.Object;
                //                   _logger.LogInformation("payment Failed: ", intent.Id);
                var pendingBooking = await _paymentService.PaymentFailed(intent.Id);

                break;
            }

            return(new EmptyResult());
        }
Exemplo n.º 18
0
        public async Task <ActionResult> StripeWebhook()
        {
            var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();

            var stripeEvent = EventUtility.ConstructEvent(json, Request.Headers["Stripe-Signature"], _whSecret);

            PaymentIntent intent;

            Core.Entities.OrderAgregate.Order order;

            switch (stripeEvent.Type)
            {
            case "payment_intent.succeeded":
                intent = (PaymentIntent)stripeEvent.Data.Object;
                _logger.LogInformation("Payment succeeded: ", intent.Id);
                order = await _paymentService.UpdateOrderPaymentSucceeded(intent.Id);

                _logger.LogInformation("Payment received to order ", order.Id);
                break;

            case "payment_intent.payment_failed":
                intent = (PaymentIntent)stripeEvent.Data.Object;
                _logger.LogInformation("Payment failed: ", intent.Id);
                order = await _paymentService.UpdateOrderPaymentFailed(intent.Id);

                _logger.LogInformation("Payment failed to order ", order.Id);
                break;
            }

            //striper wants confirmation, if he does not receive one, he will still send requests
            return(new EmptyResult());
        }
Exemplo n.º 19
0
        protected Event GetWebhookStripeEvent(HttpRequest request, string webhookSecret)
        {
            Event stripeEvent = null;

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

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

                        stripeEvent = EventUtility.ConstructEvent(json, request.Headers["Stripe-Signature"], webhookSecret, throwOnApiVersionMismatch: false);

                        HttpContext.Current.Items["TC_StripeEvent"] = stripeEvent;
                    }
                }
                catch (Exception exp)
                {
                    LoggingService.Instance.Error <BaseStripeProvider>("BaseStripeProvider - GetWebhookStripeEvent", exp);
                }
            }

            return(stripeEvent);
        }
Exemplo n.º 20
0
        public async Task <IActionResult> Index()
        {
            var json = await new StreamReader(this.HttpContext.Request.Body).ReadToEndAsync();

            try
            {
                var stripeEvent = EventUtility.ConstructEvent(
                    json,
                    this.Request.Headers["Stripe-Signature"],
                    this.configuration["Stripe:WebHookKey"]);

                // Handle the checkout.session.completed event
                if (stripeEvent.Type == Events.CheckoutSessionCompleted)
                {
                    var session = stripeEvent.Data.Object as Stripe.Checkout.Session;

                    // Fulfill the purchase...
                    if (session.PaymentStatus == "paid")
                    {
                        await this.ordersService.FulfillOrderById(session.Metadata["order_id"], session.PaymentIntentId);
                    }
                }

                return(this.Ok());
            }
            catch (StripeException)
            {
                return(this.BadRequest());
            }
        }
        public async Task <IActionResult> WebHookAsync()
        {
            var json           = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();
            var endpointSecret = "";// _configuration["Stripe:WebHookSecret"];

            try
            {
                var stripeEvent = EventUtility.ConstructEvent(json,
                                                              Request.Headers["Stripe-Signature"], endpointSecret);


                if (stripeEvent.Type == Events.AccountUpdated)
                {
                    var account = stripeEvent.Data.Object as Account;
                    //HandleAccountUpdate(account);
                    _logger.LogWarning("Web hook Post in Stripe controller at " + DateTime.Now + " data received " + account);
                    var text = JsonSerializer.Serialize(account);
                }
                else
                {
                    Console.WriteLine("Unhandled event type: {0}", stripeEvent.Type);
                }

                return(Ok());
            }
            catch (StripeException)
            {
                return(BadRequest());
            }
        }
Exemplo n.º 22
0
        public async Task <ActionResult> StripeWebhook()
        {
            var json            = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();
            var stripeSignature = Request.Headers["Stripe-Signature"];

            var stripeEvent = EventUtility.ConstructEvent(json, stripeSignature, _webhookSecret);

            PaymentIntent intent;

            Core.Entities.OrderAggregate.Order order;

            switch (stripeEvent.Type)
            {
            case "payment_intent.succeeded":
                intent = (PaymentIntent)stripeEvent.Data.Object;
                _logger.LogInformation("Payment Succeeded: ", intent.Id);
                order = await _paymentService.UpdateOrderPaymentSucceeded(intent.Id);

                _logger.LogInformation("OrderStatus updated to PaymentReceived: ", intent.Id);
                break;

            case "payment_intent.payment_failed":
                intent = (PaymentIntent)stripeEvent.Data.Object;
                _logger.LogInformation("Payment Failed: ", intent.Id);
                order = await _paymentService.UpdateOrderPaymentFailed(intent.Id);

                _logger.LogInformation("OrderStatus updated to PaymentFailed: ", intent.Id);
                break;
            }

            // Lets Stripe know we've received the event. If they don't receive this they will
            // resend over a couple of days
            return(new EmptyResult());
        }
Exemplo n.º 23
0
        public async Task <ActionResult> StripeWebhook()
        {
            var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();

            var stripeEvent = EventUtility.ConstructEvent(json, Request.Headers["Stripe-Signature"], WhSecret);

            PaymentIntent intent;

            Core.Entities.OrderAggregate.Order order;

            switch (stripeEvent.Type)
            {
            case "payment_intent.succeeded": intent = (PaymentIntent)stripeEvent.Data.Object;
                order = await paymentService.UpdateOrderPaymentSucceeded(intent.Id);

                break;

            case "payment_intent.payment_failed":  intent = (PaymentIntent)stripeEvent.Data.Object;
                order = await paymentService.UpdateOrderPaymentFailed(intent.Id);

                break;
            }

            return(new EmptyResult());
        }
Exemplo n.º 24
0
        public IActionResult ChargeChange()
        {
            var json = new StreamReader(HttpContext.Request.Body).ReadToEnd();

            try
            {
                var stripeEvent = EventUtility.ConstructEvent(json,
                                                              Request.Headers["Stripe-Signature"], WebhookSecret, throwOnApiVersionMismatch: true);
                Charge charge = (Charge)stripeEvent.Data.Object;
                switch (charge.Status)
                {
                case "succeeded":
                    //This is an example of what to do after a charge is successful
                    //charge.Metadata.TryGetValue("Product", out string Product);
                    //charge.Metadata.TryGetValue("Quantity", out string Quantity);
                    //Database.ReduceStock(Product, Quantity);
                    break;

                case "failed":
                    //Code to execute on a failed charge
                    break;
                }
            }
            catch (Exception e)
            {
                //e.Ship(HttpContext);
                return(BadRequest());
            }
            return(Ok());
        }
        [Authorize(Roles = Constants.AllUsersRole)] //The webhook needs to be accessable
        public async Task <IActionResult> Index()
        {
            string json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();

            try
            {
                var stripeEvent = EventUtility.ConstructEvent(json,
                                                              Request.Headers["Stripe-Signature"], _webhookSecret);
                switch (stripeEvent.Type)
                {
                case Events.CustomerSourceUpdated:
                    //make sure payment info is valid
                    break;

                case Events.CustomerSourceExpiring:
                    //send reminder email to update payment method
                    break;

                case Events.ChargeFailed:
                    //do something
                    break;
                }
                return(Ok());
            }
            catch (StripeException e)
            {
                return(BadRequest());
            }
        }
        public async Task <IActionResult> Webhook()
        {
            // Simple deserialization:
            // var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();
            // var stripeEvent = EventUtility.ParseEvent(json);
            // Console.WriteLine(stripeEvent);
            // Console.WriteLine(stripeEvent.Type);

            // With signature verification:
            try {
                var json            = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();
                var endpointSecret  = "whsec_***";
                var signatureHeader = Request.Headers["Stripe-Signature"];

                var stripeEvent = EventUtility.ConstructEvent(json, signatureHeader, endpointSecret);
                Console.WriteLine(stripeEvent);
                Console.WriteLine(stripeEvent.Type);

                if (stripeEvent.Type == Events.CustomerCreated)
                {
                    var customer = stripeEvent.Data.Object as Customer;
                    Console.WriteLine(customer);
                    Console.WriteLine(customer.Id);
                }
            } catch (StripeException e) {
                Console.WriteLine(e);
                return(BadRequest());
            } catch (Exception e) {
                Console.WriteLine(e);
                return(BadRequest());
            }

            return(Ok());
        }
Exemplo n.º 27
0
        public async Task <IActionResult> ProcessWebhookEvent()
        {
            var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();


            // Verify webhook signature and extract the event.
            // See https://stripe.com/docs/webhooks/signatures for more information.
            try
            {
                var stripeEvent = EventUtility.ConstructEvent(json, Request.Headers["Stripe-Signature"], webhookSecret);

                if (stripeEvent.Type == Events.PaymentIntentSucceeded)
                {
                    var paymentIntent      = stripeEvent.Data.Object as PaymentIntent;
                    var connectedAccountId = stripeEvent.Account;
                    HandleSuccessfulPaymentIntent(connectedAccountId, paymentIntent);
                    _fakelakiService.SetSuccessfullPayment(paymentIntent.Id);
                }

                return(Ok());
            }
            catch (Exception e)
            {
                _logger.LogInformation(e.ToString());
                return(BadRequest());
            }
        }
Exemplo n.º 28
0
        public async Task <IActionResult> Index()
        {
            var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();

            try
            {
                var stripeEvent = EventUtility.ConstructEvent(json,
                                                              Request.Headers["Stripe-Signature"], secret);

                // Handle the checkout.session.completed event
                if (stripeEvent.Type == Events.CheckoutSessionCompleted)
                {
                    var session = stripeEvent.Data.Object as Session;

                    // Fulfill the purchase...
                    // HandleCheckoutSession(session);
                    CompleteSession(session);
                    return(RedirectToPage("/shopstuff/chargeoutcome", "WebHook"));
                }
                else if (stripeEvent.Type == Events.PaymentIntentPaymentFailed)
                {
                    return(RedirectToPage("/shopstuff/chargeoutcome", "WebHook"));
                }
                else
                {
                    return(Ok());
                }
            }
            catch (StripeException e)
            {
                return(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 == "checkout.session.completed")
            {
                var session = stripeEvent.Data.Object as Stripe.Checkout.Session;
                Console.WriteLine($"Session ID: {session.Id}");
                // Take some action based on session.
            }

            return(Ok());
        }
Exemplo n.º 30
0
        public async Task <IActionResult> ProcessWebhookEvent()
        {
            var json = await new StreamReader(HttpContext.Request.Body).ReadToEndAsync();

            // Uncomment and replace with a real secret. You can find your endpoint's
            // secret in your webhook settings.
            // const string webhookSecret = "whsec_..."
            string webhookSecret = "whsec_...";

            // Verify webhook signature and extract the event.
            // See https://stripe.com/docs/webhooks/signatures for more information.
            try
            {
                var stripeEvent = EventUtility.ConstructEvent(json, Request.Headers["Stripe-Signature"], webhookSecret);

                if (stripeEvent.Type == Events.PaymentIntentSucceeded)
                {
                    var paymentIntent = stripeEvent.Data.Object as PaymentIntent;
                    handleSuccessfulPaymentIntent(paymentIntent);
                }

                return(Ok());
            }
            catch (Exception e)
            {
                logger.LogInformation(e.ToString());
                return(BadRequest());
            }
        }