private Subscription GetSubscription(string subscriptionId)
    {
        Guard.Against.NullOrEmpty(subscriptionId, nameof(subscriptionId));
        var subscription = _subscriptionService.Get(subscriptionId);

        return(subscription);
    }
            public void WhenGetWithUnknownId_ThenThrowsNotFound()
            {
                store.Setup(s => s.Find("auserid"))
                .Returns(new List <WebhookSubscription>());

                Assert.That(() => service.Get(new GetSubscription
                {
                    Id = "anunknownid"
                }), ThrowsHttpError.WithStatusCode(HttpStatusCode.NotFound));
            }
예제 #3
0
        private Stripe.Subscription UpdateStripeSubscriptionPlan(StripeSubUpdatePlanRequest request)
        {
            StripeConfiguration.ApiKey = _appKeys.StripeApiKey;

            var service = new SubscriptionService();

            Stripe.Subscription subscription = service.Get(request.SubscriptionId);

            var items = new List <SubscriptionItemOptions>
            {
                new SubscriptionItemOptions
                {
                    Id    = subscription.Items.Data[0].Id,
                    Price = request.PriceId,
                }
            };

            var options = new SubscriptionUpdateOptions
            {
                Items = items,
            };

            options.AddExpand("latest_invoice.payment_intent");
            subscription = service.Update(request.SubscriptionId, options);
            return(subscription);
        }
예제 #4
0
        public static bool Perform(Guild guild, DataBase db)
        {
            if (guild.DiscordId == "426894892262752256")
            {
                return(true);
            }

            if (guild.SubscriptionId != null)
            {
                var service = new SubscriptionService();
                try
                {
                    var subscription = service.Get(guild.SubscriptionId);
                    if (subscription != null && subscription.CanceledAt == null)
                    {
                        return(true);
                    }
                } catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
                guild.SubscriptionId = null;
                db.SaveChanges();
            }
            return(QueryForSubscription(guild, db));
        }
예제 #5
0
파일: Pro.cs 프로젝트: SheelaQueen/Voltaire
        public static async Task PerformAsync(ShardedCommandContext context, DataBase db)
        {
            var guild = FindOrCreateGuild.Perform(context.Guild, db);

            if (EnsureActiveSubscription.Perform(guild, db))
            {
                var service      = new SubscriptionService();
                var subscription = service.Get(guild.SubscriptionId);
                var amount       = subscription.Plan.Amount;
                var date         = subscription.CurrentPeriodEnd;

                var message = $"Your current subscription will renew {date.Value.ToLongDateString()}.\n" +
                              $"To cancel your subscription, use the `!volt cancel` command.";

                await context.Channel.SendMessageAsync(text : message);
            }
            else
            {
                var size = context.Guild.MemberCount <= 200 ? "s" : "l";
                var url  = $"https://nminchow.github.io/VoltaireWeb/upgrade?serverId={context.Guild.Id.ToString()}&type={size}";
                var view = Views.Info.Pro.Response(url, guild, db);
                try {
                    await context.Channel.SendMessageAsync(view.Item1, embed : view.Item2);
                } catch (Discord.Net.HttpException e) {
                    await context.Channel.SendMessageAsync(text : $"Use this URL to upgrade to Volatire Pro: {url}");
                }
            }
        }
        public ActionResult <InvoiceResponse> InvoicePreview(string subscriptionId, string newPriceLookupKey)
        {
            var customerId   = HttpContext.Request.Cookies["customer"];
            var service      = new SubscriptionService();
            var subscription = service.Get(subscriptionId);

            var invoiceService = new InvoiceService();
            var options        = new UpcomingInvoiceOptions
            {
                Customer          = customerId,
                Subscription      = subscriptionId,
                SubscriptionItems = new List <InvoiceSubscriptionItemOptions>
                {
                    new InvoiceSubscriptionItemOptions
                    {
                        Id    = subscription.Items.Data[0].Id,
                        Price = Environment.GetEnvironmentVariable(newPriceLookupKey.ToUpper()),
                    },
                }
            };
            Invoice upcoming = invoiceService.Upcoming(options);

            return(new InvoiceResponse {
                Invoice = upcoming,
            });
        }
예제 #7
0
        public ActionResult <Invoice> RetrieveUpcomingInvoice([FromBody] RetrieveUpcomingInvoiceRequest req)
        {
            var service      = new SubscriptionService();
            var subscription = service.Get(req.Subscription);

            var invoiceService = new InvoiceService();
            var options        = new UpcomingInvoiceOptions
            {
                Customer          = req.Customer,
                Subscription      = req.Subscription,
                SubscriptionItems = new List <InvoiceSubscriptionItemOptions>
                {
                    new InvoiceSubscriptionItemOptions
                    {
                        Id      = subscription.Items.Data[0].Id,
                        Deleted = true,
                    },
                    new InvoiceSubscriptionItemOptions
                    {
                        // TODO: This should be Price, but isnt in Stripe.net yet.
                        Plan    = Environment.GetEnvironmentVariable(req.NewPrice),
                        Deleted = false,
                    },
                }
            };
            Invoice upcoming = invoiceService.Upcoming(options);

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

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

                ConfigureStripe(secretKey);

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

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

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

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

            return(ApiResult.Empty);
        }
예제 #9
0
        private Stripe.Subscription GetStripeSubscription(string subscriptionId)
        {
            StripeConfiguration.ApiKey = _appKeys.StripeApiKey;

            var service = new SubscriptionService();
            var options = new SubscriptionGetOptions();

            options.AddExpand("default_payment_method");
            var subscription = service.Get(subscriptionId, options);

            return(subscription);
        }
예제 #10
0
        public static string ConfirmSubscription(string subscriptionId)
        {
            try
            {
                //retrieve subscription with the id
                var          service      = new SubscriptionService();
                Subscription subscription = service.Get(subscriptionId);

                //get the data for dbsave
                //each variable will do this comparison ----> ?? "" < -----
                //that comparison means "If null, place empty string)
                String SubscriptionId     = subscription.Id;
                String BillingCycleAnchor = subscription.BillingCycleAnchor?.ToString() ?? "";
                String BillingThreshold   = subscription.BillingThresholds?.ToString() ?? "";
                String CollectionMethod   = subscription.CollectionMethod ?? "";
                String CreateDate         = subscription.Created?.ToString() ?? "";
                String StartDate          = subscription.StartDate?.ToString() ?? "";
                String EndDate            = subscription.EndedAt?.ToString() ?? "";
                String CurrentPeriodStart = subscription.CurrentPeriodStart?.ToString() ?? "";
                String CurrentPeriodEnd   = subscription.CurrentPeriodEnd?.ToString() ?? "";
                String Customer           = subscription.Customer?.ToString() ?? "";
                String CustomerId         = subscription.CustomerId?.ToString() ?? "";
                String ScheduleId         = subscription.ScheduleId?.ToString() ?? "";
                String Schedule           = subscription.Schedule?.ToString() ?? "";
                String Status             = subscription.Status ?? "";
                String PlanId             = subscription.Plan.Id ?? "";
                String PlanName           = subscription.Plan.Nickname ?? "";
                String PlanInterval       = subscription.Plan.Interval ?? "";
                String PlanBillingScheme  = subscription.Plan.BillingScheme ?? "";
                String PlanAmount         = subscription.Plan.Amount?.ToString() ?? "";
                String PlanCurrency       = subscription.Plan.Currency ?? "";

                //connect to the database & save subscription
                string        cs  = WebConfigurationManager.ConnectionStrings["StripeDatabaseConnectionString"].ConnectionString;
                SqlConnection con = new SqlConnection(cs);

                //insert in db
                string sql = "INSERT INTO [SUBSCRIPTIONS](SubscriptionId, BillingCycleAnchor, BillingThreshold, CollectionMethod, CreateDate, StartDate, CurrentPeriodStart, CurrentPeriodEnd, Customer, CustomerId, ScheduleId, Schedule, Status, PlanId, PlanName, PlanInterval, PlanScheme, PlanAmount, PlanCurrency) " +
                             "VALUES('" + SubscriptionId + "', '" + BillingCycleAnchor + "', '" + BillingThreshold + "', '" + CollectionMethod + "', '" + CreateDate + "', '" + StartDate + "', '" + CurrentPeriodStart + "', '" + CurrentPeriodEnd + "', '" + Customer + "', '" + CustomerId + "', '" + ScheduleId + "', '" + Schedule + "', '" + Status + "', '" + PlanId + "', '" + PlanName + "', '" + PlanInterval + "', '" + PlanBillingScheme + "', '" + PlanAmount + "', '" + PlanCurrency + "');";
                con.Open();
                SqlCommand cmd = new SqlCommand(sql, con);

                cmd.ExecuteNonQuery();
                con.Close();

                // return subscription object as JSON back to web method
                return(JsonConvert.SerializeObject(subscription));
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        public ActionResult <RetrieveSubscriptionInformationResponse> RetrieveSubscriptionInformation([FromBody] RetrieveSubscriptionInformationRequest req)
        {
            if (!ModelState.IsValid)
            {
                return(this.FailWithMessage("invalid params"));
            }
            var options = new SubscriptionGetOptions();

            options.AddExpand("latest_invoice");
            options.AddExpand("customer.invoice_settings.default_payment_method");
            options.AddExpand("items.data.price.product");
            var          service = new SubscriptionService();
            Subscription subscription;

            try
            {
                subscription = service.Get(req.Subscription, options);
            }
            catch (StripeException e)
            {
                return(this.FailWithMessage($"Failed to retrieve subscription with ID ({req.Subscription}): {e}"));
            }

            var invoiceOptions = new UpcomingInvoiceOptions
            {
                Subscription = req.Subscription,
            };
            var     invoiceService = new InvoiceService();
            Invoice upcomingInvoice;

            try
            {
                upcomingInvoice = invoiceService.Upcoming(invoiceOptions);
            }
            catch (StripeException e)
            {
                return(this.FailWithMessage($"Failed to retrieve upcoming invoice: {e}"));
            }

            var item = subscription.Items.Data[0];

            return(new RetrieveSubscriptionInformationResponse
            {
                Card = subscription.Customer.InvoiceSettings.DefaultPaymentMethod.Card,
                ProductDescription = item.Price.Product.Name,
                CurrentPrice = item.Price.Id,
                CurrentQuantity = item.Quantity,
                LatestInvoice = subscription.LatestInvoice,
                UpcomingInvoice = upcomingInvoice,
            });
        }
예제 #12
0
        public async void Get_null_record()
        {
            var mock = new ServiceMockFacade <ISubscriptionRepository>();

            mock.RepositoryMock.Setup(x => x.Get(It.IsAny <string>())).Returns(Task.FromResult <Subscription>(null));
            var service = new SubscriptionService(mock.LoggerMock.Object,
                                                  mock.RepositoryMock.Object,
                                                  mock.ModelValidatorMockFactory.SubscriptionModelValidatorMock.Object,
                                                  mock.BOLMapperMockFactory.BOLSubscriptionMapperMock,
                                                  mock.DALMapperMockFactory.DALSubscriptionMapperMock);

            ApiSubscriptionResponseModel response = await service.Get(default(string));

            response.Should().BeNull();
            mock.RepositoryMock.Verify(x => x.Get(It.IsAny <string>()));
        }
예제 #13
0
        public async void Get_ShouldReturnNullBecauseRecordNotFound()
        {
            var mock = new ServiceMockFacade <ISubscriptionService, ISubscriptionRepository>();

            mock.RepositoryMock.Setup(x => x.Get(It.IsAny <int>())).Returns(Task.FromResult <Subscription>(null));
            var service = new SubscriptionService(mock.LoggerMock.Object,
                                                  mock.MediatorMock.Object,
                                                  mock.RepositoryMock.Object,
                                                  mock.ModelValidatorMockFactory.SubscriptionModelValidatorMock.Object,
                                                  mock.DALMapperMockFactory.DALSubscriptionMapperMock);

            ApiSubscriptionServerResponseModel response = await service.Get(default(int));

            response.Should().BeNull();
            mock.RepositoryMock.Verify(x => x.Get(It.IsAny <int>()));
        }
        public override string GetCartNumber(HttpRequest request, IDictionary <string, string> settings)
        {
            var cartNumber = "";

            try
            {
                request.MustNotBeNull("request");
                settings.MustNotBeNull("settings");

                // If in test mode, write out the form data to a text file
                if (settings.ContainsKey("mode") && settings["mode"] == "test")
                {
                    LogRequest <StripeSubscription>(request, logPostData: true);
                }

                // Get the current stripe api key based on mode
                var apiKey = settings[settings["mode"] + "_secret_key"];

                var stripeEvent = GetStripeEvent(request);

                // We are only interested in charge events
                if (stripeEvent != null && stripeEvent.Type.StartsWith("invoice."))
                {
                    var invoice = Mapper <Invoice> .MapFromJson(stripeEvent.Data.Object.ToString());

                    if (!string.IsNullOrWhiteSpace(invoice.SubscriptionId))
                    {
                        var subscriptionService = new SubscriptionService(apiKey);
                        var subscription        = subscriptionService.Get(invoice.SubscriptionId);
                        if (subscription?.Metadata != null && subscription.Metadata.ContainsKey("cartNumber"))
                        {
                            cartNumber = subscription.Metadata["cartNumber"];
                        }
                    }
                }
                else
                {
                    HttpContext.Current.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                }
            }
            catch (Exception exp)
            {
                LoggingService.Instance.Error <StripeSubscription>("StripeSubscription - GetCartNumber", exp);
            }

            return(cartNumber);
        }
        public async Task <string> SendNotification(string user, string message)
        {
            var sendRequest = new SendRequest {
                Message = message
            };

            try
            {
                var subscription = SubscriptionService.Get(user);
                var result       = await PushService.SendNotification(subscription, sendRequest);

                return(result.ToString());
            }
            catch (Exception e)
            {
                return(e.Message);
            }
        }
예제 #16
0
        public void RawJObject()
        {
            var service      = new SubscriptionService(this.StripeClient);
            var subscription = service.Get("sub_123");

            Assert.NotNull(subscription);

            // Access `id`, a string element
            Assert.Equal(subscription.Id, subscription.RawJObject["id"]);

            // Access `created`, a number element
            Assert.Equal(subscription.Created, subscription.RawJObject["created"]);

            // Access `items[data][0][id]`, a deeply nested string element
            Assert.Equal(
                subscription.Items.Data[0].Id,
                subscription.RawJObject["items"]["data"][0]["id"]);
        }
        public override CallbackInfo ProcessCallback(Order order, HttpRequest request, IDictionary <string, string> settings)
        {
            try
            {
                order.MustNotBeNull("order");
                request.MustNotBeNull("request");
                settings.MustNotBeNull("settings");
                settings.MustContainKey("billing_mode", "settings");

                // Because we need more fine grained control over the callback process
                // we actually perform all the callback functionality from within the
                // ProcessRequest method instead. We only really use the callback
                // function for when the billing mode is invoice as this means
                // that the payment screen won't have been displayed and so the
                // stripe subscription won't have been setup yet and so we need to
                // do it now.
                var billingMode = settings["billing_mode"];

                ValidateBillingModeSetting(billingMode);

                if (billingMode == "invoice")
                {
                    ProcessCaptureRequest(order, request, settings);

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

                    ConfigureStripe(apiKey);

                    var subscriptionService = new SubscriptionService();
                    var subscription        = subscriptionService.Get(order.Properties["stripeSubscriptionId"]);
                    var invoice             = subscription.LatestInvoice ?? new InvoiceService().Get(subscription.LatestInvoiceId);

                    return(new CallbackInfo(CentsToDollars(invoice.AmountDue), invoice.Id, PaymentState.Authorized));
                }
            }
            catch (Exception exp)
            {
                LoggingService.Instance.Error <StripeSubscription>("StripeSubscription(" + order.CartNumber + ") - ProcessCallback", exp);
            }

            return(null);
        }
예제 #18
0
        public ActionResult<Subscription> UpdateSubscription([FromBody] UpdateSubscriptionRequest req)
        {
            var service = new SubscriptionService();
            var subscription = service.Get(req.Subscription);

            var options = new SubscriptionUpdateOptions
            {
                CancelAtPeriodEnd = false,
                Items = new List<SubscriptionItemOptions>
                {
                    new SubscriptionItemOptions
                    {
                        Id = subscription.Items.Data[0].Id,
                        Price = Environment.GetEnvironmentVariable(req.NewPrice),
                    }
                }
            };
            var updatedSubscription = service.Update(req.Subscription, options);
            return updatedSubscription;
        }
예제 #19
0
        public IActionResult Upgrade(string subKey, string plan)
        {
            // Set your secret key. Remember to switch to your live secret key in production!
            // See your keys here: https://dashboard.stripe.com/account/apikeys
            StripeConfiguration.ApiKey = _configuration["Stripe:SecretKey"];

            var          service      = new SubscriptionService();
            Subscription subscription = service.Get(subKey);

            var planId = _configuration["Stripe:Daily5"];

            if (plan == "Daily10")
            {
                planId = _configuration["Stripe:Daily10"];
            }

            var items = new List <SubscriptionItemOptions> {
                new SubscriptionItemOptions {
                    Id    = subscription.Items.Data[0].Id,
                    Price = planId,
                },
            };

            var options = new SubscriptionUpdateOptions
            {
                CancelAtPeriodEnd = false,
                ProrationBehavior = "create_prorations",
                Items             = items,
            };

            subscription = service.Update(subKey, options);

            var subUpdate = _database.Subscriptions.Where(i => i.SubID == subKey).Single();

            subUpdate.PlanID = planId;

            _database.SaveChanges();
            return(View("UpdateResult"));
        }
예제 #20
0
        public static async Task PerformAsync(ShardedCommandContext context, DataBase db)
        {
            var guild = FindOrCreateGuild.Perform(context.Guild, db);

            if (EnsureActiveSubscription.Perform(guild, db))
            {
                var service      = new SubscriptionService();
                var subscription = service.Get(guild.SubscriptionId);
                var amount       = subscription.Plan.Amount;
                var date         = subscription.CurrentPeriodEnd;

                var message = $"Your current subscription will renew {date.Value.ToLongDateString()}.\n" +
                              $"To cancel your subscription, use the `!volt cancel` command.";

                await context.Channel.SendMessageAsync(text : message);
            }
            else
            {
                var size = context.Guild.MemberCount <= 200 ? "s" : "l";
                //var url = $"https://nminchow.github.io/VoltaireWeb/upgrade?serverId={context.Guild.Id.ToString()}&type={size}";
                var url = $"CURRENTLY NOT SUPPORTED (but everybody is pro anyway <3 )";
                await context.Channel.SendMessageAsync(text : $"Use this URL to upgrade to Volatire Pro: {url}");
            }
        }
        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);
        }
예제 #22
0
        public Subscription GetSubscription(string subscriptionId)
        {
            var subscriptionService = new SubscriptionService();

            return(subscriptionService.Get(subscriptionId));
        }
        private Stripe.Subscription GetSubscription(string subscriptionId)
        {
            var subscription = _subscriptionService.Get(subscriptionId);

            return(subscription);
        }
예제 #24
0
        public override CallbackResult ProcessCallback(OrderReadOnly order, HttpRequestBase request, StripeCheckoutSettings 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)
                    {
                        if (stripeSession.Mode == "payment")
                        {
                            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 },
                                { "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        = subscriptionService.Get(stripeSession.SubscriptionId, new SubscriptionGetOptions
                            {
                                Expand = new List <string>(new[] {
                                    "latest_invoice",
                                    "latest_invoice.charge",
                                    "latest_invoice.payment_intent"
                                })
                            });
                            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 }
                            }));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Vendr.Log.Error <StripeCheckoutOneTimePaymentProvider>(ex, "Stripe - ProcessCallback");
            }

            return(CallbackResult.BadRequest());
        }
        public ActionResult <UpdateSubscriptionResponse> UpdateSubscription([FromBody] UpdateSubscriptionRequest req)
        {
            if (!ModelState.IsValid)
            {
                return(this.FailWithMessage("invalid params"));
            }
            var newPrice = Environment.GetEnvironmentVariable(req.NewPrice);

            if (newPrice is null || newPrice == "")
            {
                return(this.FailWithMessage($"No price with the new price ID ({req.NewPrice}) found in .env"));
            }

            var          service = new SubscriptionService();
            Subscription subscription;

            try
            {
                subscription = service.Get(req.Subscription);
            }
            catch (StripeException e)
            {
                return(this.FailWithMessage($"Failed to retrieve subscription: {e}"));
            }
            var currentPrice = subscription.Items.Data[0].Price.Id;

            List <SubscriptionItemOptions> items;

            if (currentPrice == newPrice)
            {
                items = new List <SubscriptionItemOptions>
                {
                    new SubscriptionItemOptions
                    {
                        Id       = subscription.Items.Data[0].Id,
                        Quantity = req.Quantity,
                    },
                };
            }
            else
            {
                items = new List <SubscriptionItemOptions>
                {
                    new SubscriptionItemOptions
                    {
                        Id      = subscription.Items.Data[0].Id,
                        Deleted = true,
                    },
                    new SubscriptionItemOptions
                    {
                        Price    = newPrice,
                        Quantity = req.Quantity,
                    },
                };
            }

            var options = new SubscriptionUpdateOptions
            {
                CancelAtPeriodEnd = false,
                Items             = items,
                ProrationBehavior = "always_invoice",
            };
            var updatedSubscription = service.Update(req.Subscription, options);

            return(new UpdateSubscriptionResponse
            {
                Subscription = updatedSubscription,
            });
        }
        public ActionResult <RetrieveUpcomingInvoiceResponse> RetrieveUpcomingInvoice([FromBody] RetrieveUpcomingInvoiceRequest req)
        {
            if (!ModelState.IsValid)
            {
                return(this.FailWithMessage("invalid params"));
            }
            var newPrice = Environment.GetEnvironmentVariable(req.NewPrice.ToUpper());

            if (newPrice is null || newPrice == "")
            {
                return(this.FailWithMessage($"No price with the new price ID ({req.NewPrice}) found in .env"));
            }

            List <InvoiceSubscriptionItemOptions> items;
            Subscription subscription = null;

            if (req.Subscription != "" && req.Subscription != null)
            {
                var subscriptionService = new SubscriptionService();
                subscription = subscriptionService.Get(req.Subscription);

                var currentPrice = subscription.Items.Data[0].Price.Id;
                if (currentPrice == newPrice)
                {
                    items = new List <InvoiceSubscriptionItemOptions> {
                        new InvoiceSubscriptionItemOptions
                        {
                            Id       = subscription.Items.Data[0].Id,
                            Quantity = req.Quantity,
                        }
                    };
                }
                else
                {
                    items = new List <InvoiceSubscriptionItemOptions> {
                        new InvoiceSubscriptionItemOptions
                        {
                            Id      = subscription.Items.Data[0].Id,
                            Deleted = true,
                        },
                        new InvoiceSubscriptionItemOptions
                        {
                            Price    = newPrice,
                            Quantity = req.Quantity,
                        },
                    };
                }
            }
            else
            {
                items = new List <InvoiceSubscriptionItemOptions> {
                    new InvoiceSubscriptionItemOptions
                    {
                        Price    = newPrice,
                        Quantity = req.Quantity,
                    },
                };
            }

            var invoiceService = new InvoiceService();
            var options        = new UpcomingInvoiceOptions
            {
                Customer          = req.Customer,
                Subscription      = req.Subscription,
                SubscriptionItems = items,
            };
            Invoice upcomingInvoice = invoiceService.Upcoming(options);

            if (req.Subscription == "" || req.Subscription is null)
            {
                return(new RetrieveUpcomingInvoiceResponse
                {
                    Invoice = upcomingInvoice,
                });
            }
            else
            {
                var  currentPeriodEnd = subscription.CurrentPeriodEnd;
                long immediateTotal   = 0;
                long nextInvoiceSum   = 0;
                foreach (var lineItem in upcomingInvoice.Lines.Data)
                {
                    if (lineItem.Period.End == currentPeriodEnd)
                    {
                        immediateTotal += lineItem.Amount;
                    }
                    else
                    {
                        nextInvoiceSum += lineItem.Amount;
                    }
                }

                return(new RetrieveUpcomingInvoiceResponse
                {
                    ImmediateTotal = immediateTotal,
                    NextInvoiceSum = nextInvoiceSum,
                    Invoice = upcomingInvoice,
                });
            }
        }
예제 #27
0
 public Subscription Get(string customerId, string subscriptionId)
 {
     return(_stripeSubscriptionService.Get(subscriptionId));
 }
예제 #28
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);
        }