Exemple #1
0
        public List <Charge> List()
        {
            //StripeConfiguration.SetApiKey(_config.GetSection("api_key").Value);

            var service = new ChargeService();

            var optionsl = new ChargeListOptions
            {
                Limit = 100,
            };
            var orders = service.List(optionsl);

            foreach (var order in orders)
            {
                var services = new ChargeService();
                var options  = new ChargeGetOptions();
                options.AddExpand("customer");
                options.AddExpand("order");
                var charge = service.Get(order.Id, options);
                order.Created        = charge.Created.Date;
                order.Amount         = charge.Amount;
                order.AmountRefunded = charge.AmountRefunded;
                if (order.Customer != null)
                {
                    if (charge.Customer.Email == "*****@*****.**")
                    {
                        charge.Customer.Email = "";
                    }
                }
            }
            return(orders.Data);
        }
Exemple #2
0
        private static void Main(string[] args)
        {
            var apiKey = "";
            var stripe = new StripeClient(apiKey);

            var chargeService = new ChargeService(stripe);
            var chargeId      = "";
            var charge        = chargeService.Get(chargeId);

            Console.WriteLine("Charge");
            Console.WriteLine($"Amount: ${charge.Amount}");

            var payoutService = new PayoutService(stripe);
            var payoutId      = "";
            var payout        = payoutService.Get(payoutId);

            Console.WriteLine($"Payout: {payoutId}");
            Console.WriteLine($"Date Paid: {payout.ArrivalDate.ToString()}");


            var balanceTransactionService = new BalanceTransactionService(stripe);
            var requestOptions            = new BalanceTransactionListOptions {
                Payout = payoutId, Limit = 100
            };
            var transactionList = balanceTransactionService.List(requestOptions);

            Console.WriteLine($"Transactions: {transactionList.Count()}");
        }
Exemple #3
0
        public static Charge GetByIdCharge(string id)
        {
            // Set your secret key: remember to change this to your live secret key in production
            // See your keys here: https://dashboard.stripe.com/account/apikeys
            StripeConfiguration.SetApiKey(SecretKey);

            var service = new ChargeService();
            var charge  = service.Get(id);

            return(charge);
        }
        public T GetPaymentHistory(string id)
        {
            //TestCard
            //This token is ideally supposed to come from client,
            //however being that there is no client at the moment, i am generating a token on the server side.
            StripeConfiguration.ApiKey = _stripePaymentGatewayConfiguration.SecreteKey;

            var chargeService = new ChargeService();
            var charge        = chargeService.Get(id);

            return((T)charge);
        }
        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);
        }
Exemple #6
0
        public bool ProcessPayment(Card creditCard)
        {
            StripeConfiguration.ApiKey = publishableApiKey;
            var chargeId = CreateCharge(creditCard);

            var options = new RequestOptions
            {
                ApiKey = secretKey
            };
            var    service = new ChargeService();
            Charge charge  = service.Get(
                chargeId, null,
                options
                );

            return(charge.Status == SuccessStatus ? true : false);
        }
        public IActionResult ChargeResult(string chargeId)
        {
            try
            {
                Charge charge = _chargeService.Get(chargeId);
                return(View(charge));
            }
            catch (Exception e)
            {
                var log = _logService.Get(0);
                log.Date    = DateTime.Now;
                log.LogType = "Error Occurred";
                log.Summary = $"Charge ID:{chargeId} - {JsonConvert.SerializeObject(e.ToString())}";
                _logService.Add(log);

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

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

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

                ConfigureStripe(apiKey);

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

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

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

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

            return(null);
        }
        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);
        }
Exemple #10
0
        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"];

                var chargeService = new ChargeService(apiKey);
                var charge        = chargeService.Get(order.TransactionInformation.TransactionId);

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

            return(null);
        }
Exemple #11
0
        private Transfer TransferCharge(string chargeId, string accountId)
        {
            StripeConfiguration.ApiKey = _appKeys.StripeApiKey;

            var chargeService = new ChargeService();
            var charge        = chargeService.Get(chargeId);

            long   chargeAmount = charge.Amount;
            double fee          = chargeAmount * .05; // collecting a 5% for charge
            long   amountFee    = Convert.ToInt64(fee);

            var options = new TransferCreateOptions
            {
                Amount            = chargeAmount - amountFee,
                Currency          = "usd",
                SourceTransaction = chargeId,
                Destination       = accountId,
                Description       = "Appointment transfer",
            };
            var transferService = new TransferService();
            var transfer        = transferService.Create(options);

            return(transfer);
        }
        public List <Tuple <int, bool> > Update(OrderViewModel model)
        {
            bool   res        = true; //For return Response if false
            double TotalPrice = 0;    //For calculating Total Price after Deduction from exisiting one

            //For Calculating Price if quantity changes
            //Quantity of Item Should Update in DB
            var ListForPrice = new List <Tuple <int, int> >();
            //List of items which Quantity Increases or decreses
            //Quantity of Item Should Update in DB
            var modifiedItemsAdded   = new List <Products>();
            var modifiedItemsRemoved = new List <Products>();

            var data = context.Order.Include(x => x.Charges).Include(x => x.Cus_model).Include(x => x.Cus_model.Address).Where(x => x.order_id == model.order_id).FirstOrDefault();

            if (data == null)
            {
                return new List <Tuple <int, bool> >()
                       {
                           new Tuple <int, bool>(0, false)
                       }
            }
            ;

            var ProductsList = context.Products.Where(x => x.order_id == model.order_id).Select(x => new Products()
            {
                id       = x.id,
                Quantity = x.Quantity,
                modelId  = x.modelId,
                order_id = x.order_id,
                price    = x.price
            }).ToList();

            model.Products.ForEach(x => x.order_id = data.order_id);

            //Quantity of Item Should Update in DB as well as add it to as Order with status completed
            var NewItems = model.Products.Except(model.Products.Where(o => ProductsList.Select(s => s.modelId).ToList().Contains(o.modelId)));
            //Quantity of Item Should Update in DB as well as remove it to from Order Table.
            var RemoveItems = ProductsList.Except(ProductsList.Where(o => model.Products.Select(s => s.modelId).ToList().Contains(o.modelId)));

            ListForPrice = util.Price(model.Products.Select(x => x.modelId).ToArray());
            if (model.store_id != data.store_id)
            {
                //Working For Checking Quantity Changes. If changes update Product table with Quantity and Prices
                foreach (var item in model.Products)
                {
                    var found = ProductsList.FirstOrDefault(x => x.modelId == item.modelId);
                    if (found != null)
                    {
                        if (item.Quantity > found.Quantity)
                        {
                            int PriceOfEach = ListForPrice.FirstOrDefault(x => x.Item1 == found.modelId).Item2;
                            TotalPrice    += PriceOfEach * (item.Quantity - found.Quantity);
                            found.Quantity = item.Quantity;
                            found.price    = PriceOfEach * item.Quantity;
                            modifiedItemsAdded.Add(found);
                        }
                        else if (item.Quantity < found.Quantity)
                        {
                            int PriceOfEach = ListForPrice.FirstOrDefault(x => x.Item1 == found.modelId).Item2;
                            TotalPrice    -= PriceOfEach * (found.Quantity - item.Quantity);
                            found.Quantity = item.Quantity;
                            found.price    = PriceOfEach * item.Quantity;
                            modifiedItemsRemoved.Add(found);
                        }
                    }
                }
            }
            else
            {
                //Working For Checking Quantity Changes. If changes update Product table with Quantity and Prices
                foreach (var p in model.Products)
                {
                    var found = ProductsList.FirstOrDefault(y => y.modelId == p.modelId);
                    if (found != null)
                    {
                        if (found.Quantity > p.Quantity)
                        {
                            int PriceOfEach = ListForPrice.FirstOrDefault(x => x.Item1 == found.modelId).Item2;
                            TotalPrice    -= PriceOfEach * (found.Quantity - p.Quantity);
                            found.Quantity = p.Quantity;
                            found.price    = PriceOfEach * p.Quantity;
                            modifiedItemsRemoved.Add(found);
                        }
                        else if (found.Quantity < p.Quantity)
                        {
                            int PriceOfEach = ListForPrice.FirstOrDefault(x => x.Item1 == found.modelId).Item2;
                            TotalPrice    += PriceOfEach * (p.Quantity - found.Quantity);
                            found.Quantity = p.Quantity;
                            found.price    = PriceOfEach * p.Quantity;
                            modifiedItemsAdded.Add(found);
                        }
                    }
                }
            }

            //If Status is not Completed we dont need to Check for Any Quantity Exist
            if (data.status == Status.Completed)
            {
                //checking For Quantity
                if (data.store_id != model.store_id)
                {
                    List <Tuple <int, bool> > quantityCheck = util.checkingquantity(model.Products, model.store_id);
                    if (quantityCheck.Any(x => x.Item2 == false))
                    {
                        return(quantityCheck);
                    }
                }
                //Updating Product Table if any exisitng item quantity changes(Added)
                if (modifiedItemsAdded.Count != 0)
                {
                    //Checking For Stock Exist or not?
                    if (data.store_id == model.store_id)
                    {
                        var quantityCheck = util.checkingquantity(modifiedItemsAdded, model.store_id);
                        if (quantityCheck.Any(x => x.Item2 == false))
                        {
                            return(quantityCheck);
                        }
                    }
                    var dataModel = modifiedItemsAdded.Select(x => new Model.Order.Product()
                    {
                        id      = x.id,
                        modelId = x.modelId,
                        //Phoneid = x.Phoneid,
                        price    = x.price,
                        Quantity = x.Quantity,
                        order_id = x.order_id
                    }).ToList();
                    context.Products.UpdateRange(dataModel);
                }
                //Updating Product Table if any exisitng item quantity changes(removed)
                if (modifiedItemsRemoved.Count != 0)
                {
                    var dataModel = modifiedItemsRemoved.Select(x => new Model.Order.Product()
                    {
                        id      = x.id,
                        modelId = x.modelId,
                        //Phoneid = x.Phoneid,
                        price    = x.price,
                        Quantity = x.Quantity,
                        order_id = x.order_id
                    }).ToList();
                    context.Products.UpdateRange(dataModel);
                }
                //Add New Items To Product Table if added
                if (NewItems != null)
                {
                    if (data.store_id == model.store_id)
                    {
                        var quantityCheck = util.checkingquantity(NewItems.ToList(), model.store_id);
                        if (quantityCheck.Any(x => x.Item2 == false))
                        {
                            return(quantityCheck);
                        }
                    }
                    var dataModel = NewItems.Select(x => new Model.Order.Product()
                    {
                        modelId  = x.modelId,
                        price    = ListForPrice.FirstOrDefault(p => p.Item1 == x.modelId).Item2 *x.Quantity,
                        Quantity = x.Quantity,
                        order_id = x.order_id
                    }).ToList();
                    TotalPrice += dataModel.Sum(x => x.price);
                    context.Products.AddRange(dataModel);
                }
                //Removing Exisiting Items from Product Table if removed
                if (RemoveItems != null)
                {
                    var dataModel = RemoveItems.Select(x => new Model.Order.Product()
                    {
                        id       = x.id,
                        modelId  = x.modelId,
                        order_id = x.order_id,
                        Quantity = x.Quantity
                    });
                    TotalPrice -= RemoveItems.Sum(x => x.price);
                    context.Products.RemoveRange(dataModel);
                }
            }
            else
            {
                if (modifiedItemsAdded.Count != 0)
                {
                    var dataModel = modifiedItemsAdded.Select(x => new Model.Order.Product()
                    {
                        id      = x.id,
                        modelId = x.modelId,
                        //Phoneid = x.Phoneid,
                        price    = x.price,
                        Quantity = x.Quantity,
                        order_id = x.order_id
                    }).ToList();
                    context.Products.UpdateRange(dataModel);
                }
                //Updating Product Table if any exisitng item quantity changes(removed)
                if (modifiedItemsRemoved.Count != 0)
                {
                    var dataModel = modifiedItemsRemoved.Select(x => new Model.Order.Product()
                    {
                        id      = x.id,
                        modelId = x.modelId,
                        //Phoneid = x.Phoneid,
                        price    = x.price,
                        Quantity = x.Quantity,
                        order_id = x.order_id
                    }).ToList();
                    context.Products.UpdateRange(dataModel);
                }
                //Add New Items To Product Table if added
                if (NewItems.Count() != 0)
                {
                    var dataModel = NewItems.Select(x => new Model.Order.Product()
                    {
                        modelId = x.modelId,
                        //Phoneid = x.Phoneid,
                        price    = ListForPrice.FirstOrDefault(p => p.Item1 == x.modelId).Item2 *x.Quantity,
                        Quantity = x.Quantity,
                        order_id = x.order_id
                    }).ToList();
                    TotalPrice += dataModel.Sum(x => x.price);
                    context.Products.AddRange(dataModel);
                }
                //Removing Exisiting Items from Product Table if removed
                if (RemoveItems.Count() != 0)
                {
                    var dataModel = RemoveItems.Select(x => new Model.Order.Product()
                    {
                        id       = x.id,
                        modelId  = x.modelId,
                        order_id = x.order_id,
                        Quantity = x.Quantity
                    });
                    TotalPrice -= RemoveItems.Sum(x => x.price);
                    context.Products.RemoveRange(dataModel);
                }
            }

            if (TotalPrice > 0)
            {
                if (data.PaymentMethod == PaymentMethods.Stripe)
                {
                    var Options = new ChargeCreateOptions
                    {
                        Amount      = Convert.ToInt32(TotalPrice * 0.63),
                        Currency    = "usd",
                        Description = "Customer Ref: " + model.CustRef,
                        Source      = model.stripeToken
                    };
                    var    service = new ChargeService();
                    Charge charge  = service.Create(Options);
                    if (charge.BalanceTransactionId == null || charge.Status.ToLower() != "succeeded")
                    {
                        return(new List <Tuple <int, bool> >()
                        {
                            new Tuple <int, bool>(-2, false)
                        });
                    }
                    else
                    {
                        logger.LogInformation(TotalPrice + "Charged from " + model.CustRef);
                        OrderCharges o = new OrderCharges()
                        {
                            ChargeId = charge.Id,
                            priority = data.Charges.Max(x => x.priority) + 1,
                            order_id = data.order_id
                        };
                        data.Charges.Add(o);
                    }
                }
            }
            else if (TotalPrice < 0)
            {
                if (data.PaymentMethod == PaymentMethods.Stripe)
                {
                    int count = 0;
                    TotalPrice = Math.Abs(TotalPrice);
                    logger.LogCritical(TotalPrice + "Should be Refunded To " + model.CustRef);
                    double Amount        = (TotalPrice * 0.63) - ((1 / 100) * TotalPrice);
                    double AmountToCut   = 0;
                    double Remaining     = Amount;
                    var    ChargeService = new ChargeService();
                    var    service       = new RefundService();
                    foreach (var charge in data.Charges.OrderBy(x => x.priority))
                    {
                        count++;
                        try
                        {
                            var    charg        = ChargeService.Get(charge.ChargeId);
                            double ChargeAmount = charg.Amount - charg.AmountRefunded;
                            if (Amount > ChargeAmount)
                            {
                                AmountToCut = ChargeAmount;
                            }
                            else if (Amount < ChargeAmount)
                            {
                                AmountToCut = Amount;
                            }
                            else
                            {
                                AmountToCut = Amount;
                            }
                            var options = new RefundCreateOptions
                            {
                                Charge = charge.ChargeId,
                                Amount = Convert.ToInt64(AmountToCut)
                            };
                            Refund refund = service.Create(options);
                            Amount -= AmountToCut;
                            logger.LogCritical(AmountToCut + "Refunded To " + model.CustRef + "Date" + DateTime.Now);
                            if (refund != null && Amount <= 0)
                            {
                                break;
                            }
                        }
                        catch (StripeException e)
                        {
                            switch (e.StripeError.ErrorType)
                            {
                            case "api_connection_error":
                                logger.LogError("Connection Error Occured in Reefunding To " + model.CustRef + "Date" + DateTime.Now);
                                return(new List <Tuple <int, bool> >()
                                {
                                    new Tuple <int, bool>(-2, false)
                                });

                            case "api_error":
                                logger.LogError("Connection Error Occured in Reefunding To " + model.CustRef + "Date" + DateTime.Now);
                                return(new List <Tuple <int, bool> >()
                                {
                                    new Tuple <int, bool>(-2, false)
                                });
                            }
                            if (data.Charges.Count == count)
                            {
                                return(new List <Tuple <int, bool> >()
                                {
                                    new Tuple <int, bool>(-2, false)
                                });
                            }
                        }
                    }
                }
            }

            data.Cus_model.cus_name  = model.cus_name;
            data.Cus_model.cus_phone = model.cus_phone;
            if (model.StrretAddress != null)
            {
                data.Cus_model.Address = new Address()
                {
                    City          = util.getCities().FirstOrDefault(x => x.id == model.CityId).city,
                    StreetAddress = model.StrretAddress
                };
            }
            data.store_id = model.store_id;

            context.Order.Update(data);
            //context.Entry(data).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
            context.SaveChanges();

            //Updating Stock after Checking payments
            if ((int)data.status >= 1)
            {
                if (data.store_id != model.store_id)
                {
                    res = util.updatequan(model.Products, model.store_id, "Subtract");
                    if (res == false)
                    {
                        GenerateError(model.Products, model.store_id, "Subtract");
                    }
                    res = util.updatequan(ProductsList, data.store_id, "Add");
                    if (res == false)
                    {
                        GenerateError(ProductsList, data.store_id, "Add");
                    }
                }
                else
                {
                    if (modifiedItemsAdded.Count != 0)
                    {
                        res = util.updatequan(modifiedItemsAdded, model.store_id, "Subtract");
                        if (res == false)
                        {
                            GenerateError(modifiedItemsAdded, model.store_id, "Subtract");
                        }
                    }
                    if (modifiedItemsRemoved.Count != 0)
                    {
                        res = util.updatequan(modifiedItemsRemoved, model.store_id, "Add");
                        if (res == false)
                        {
                            GenerateError(modifiedItemsRemoved, model.store_id, "Add");
                        }
                    }
                    if (NewItems != null)
                    {
                        res = util.updatequan(NewItems.ToList(), model.store_id, "Subtract");
                        if (res == false)
                        {
                            GenerateError(NewItems.ToList(), model.store_id, "Subtract");
                        }
                    }
                    if (RemoveItems != null)
                    {
                        res = util.updatequan(RemoveItems.ToList(), model.store_id, "Add");
                        if (res == false)
                        {
                            GenerateError(RemoveItems.ToList(), model.store_id, "Add");
                        }
                    }
                }
            }
            return(new List <Tuple <int, bool> >()
            {
                new Tuple <int, bool>(data.order_id, true)
            });
        }
 public Charge Get(string chargeId)
 {
     return(_stripeChargeService.Get(chargeId));
 }
Exemple #14
0
 internal Charge GetStripeCharge(PartnerInvoiceDTO invoice, ChargeService chargeService) => chargeService.Get(invoice.StripeId);
        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);
        }
Exemple #16
0
        public ActionResult StripePayment([Bind(Include = "PaymentNo,PaymentMethod,BillingAddress,Forename,Surname,CardNumber,SecurityCode,ExpiryDate,PatientId,InvoiceNo,SelectedMethod,InvoiceTotal")] CreatePaymentViewModel payment, string stripeEmail, string stripeToken)
        {
            try
            {
                //attributes
                StripeConfiguration.SetApiKey("sk_test_fHaiXwbfFo3YUowus0cFNdOR00HHNl42Yw");
                var customers = new CustomerService();
                var charges   = new ChargeService();

                //create customer
                var customer = customers.Create(new CustomerCreateOptions
                {
                    Email       = stripeEmail,
                    Description = "test purposes Charge",
                    SourceToken = stripeToken,
                });

                //creates charge, unable to correctly record charge as amount requires a long input which my entire project relises on double

                //most tiresome double to list of char to string to int64 casting ever, but succeeds in turing a double to a long compatable with stripe API
                //create list of char from invoice total
                List <char> chartotal = payment.InvoiceTotal.ToString("C2").ToList();

                //scans through char list removing all decimal points
                while (chartotal.Contains('.') || chartotal.Contains(',') || chartotal.Contains('£'))
                {
                    try
                    {
                        chartotal.Remove('.');
                        chartotal.Remove(',');
                        chartotal.Remove('£');
                    }
                    catch
                    {
                        continue;
                    }
                }

                //utalizes stringbuilder to build a string out of the list of char values
                string temptotal = null;
                var    builder   = new StringBuilder();

                foreach (char c in chartotal)
                {
                    builder.Append(c);
                }

                //final string product of the tiresome cast that now must be converted to long below
                temptotal = builder.ToString();
                //

                //create charge
                var charge = charges.Create(new ChargeCreateOptions
                {
                    Amount       = Int64.Parse(temptotal),
                    Description  = "test purposes Charge",
                    Currency     = "gbp",
                    CustomerId   = customer.Id,
                    ReceiptEmail = customer.Email,
                });

                //if charge and customer creation successfull and can be found on stripe then payment is recorded in database
                if (customers.Get(customer.Id) != null && charges.Get(charge.Id) != null)
                {
                    //transfers details from payment view model and finds invoice
                    Payment temppayment = new Payment {
                        Forename = payment.Forename, Surname = payment.Surname, BillingAddress = payment.BillingAddress, PaymentMethod = payment.SelectedMethod
                    };
                    BillingInvoice billingInvoice = db.BillingInvoices.Find(payment.InvoiceNo);

                    Patient patient = db.Patients.Find(billingInvoice.PatientID);

                    //email process
                    if (patient.Email != null)
                    {
                        EmailService emailService = new EmailService();
                        emailService.SendAsync(new IdentityMessage {
                            Destination = patient.Email, Body = "Your Payment of £" + payment.InvoiceTotal + " for your treatments has been recived", Subject = "Confirmation of Payment"
                        });
                    }

                    //transfers total to payment
                    temppayment.PaymentAmount = billingInvoice.TotalDue;

                    //creates payment
                    db.Payments.Add(temppayment);

                    db.SaveChanges();

                    //assosiates payment with invoice then updates
                    billingInvoice.PaymentRecived = true;
                    billingInvoice.PaymentNo      = temppayment.PaymentNo;

                    db.Entry(billingInvoice).State = EntityState.Modified;

                    db.SaveChanges();

                    return(RedirectToAction("Index", "BillingInvoiceManagement", new { payment.PatientId }));
                }
                else
                {
                    //stripe error message
                    ViewBag.ErrorMessage = "Unable to Process Stripe Payment";
                    return(View(payment));
                }
            }
            catch
            {
                //stripe fault error message
                ViewBag.ErrorMessage = "Error encountered during stripe payment";
                return(View(payment));
            }
        }
        private void LoadOrderButton_Click(object sender, EventArgs e)
        {
            try
            {
                /*
                 * Using Stripe's library to make request
                 * Everything below is from the Official Documentation
                 * From https://stripe.com/docs/api
                 *
                 */

                //Getting Order Information Requires SecretKey
                StripeConfiguration.ApiKey = MainForm.SecretKey;

                //Requesting OrderID
                var service = new ChargeService();
                var charge  = service.Get(OrderIDBox.Text);

                // ch_1EsuztCIBcsdGnqpOaZo2O4M

                /* Setting Metadata is a little harder so i didnt do it here.
                 * You would have to find a way to set JSON Stream into a dictionary list of find another way to store it
                 * Setting TextBox Values
                 */
                EmailBox.Text       = charge.ReceiptEmail;
                CardNoBox.Text      = charge.PaymentMethodDetails.Card.Brand;
                MonthExpiry.Text    = charge.PaymentMethodDetails.Card.ExpMonth.ToString();
                YearExpiry.Text     = charge.PaymentMethodDetails.Card.ExpYear.ToString();
                OrderStatusBox.Text = charge.Status;
                AmountBox.Text      = charge.Amount.ToString();
                DescBox.Text        = charge.Description;
                CurrencyBox.Text    = charge.Currency;
                FeeBox.Text         = charge.ApplicationFeeAmount.ToString();
                MessageBox.Show("Retreived Order");
            }
            catch (StripeException ex)
            {
                //Switch Statement is from API Documentation
                switch (ex.StripeError.ErrorType)
                {
                case "card_error":
                    MessageBox.Show("Code: " + ex.StripeError.Code + " Message: " + ex.Message);
                    break;

                case "api_connection_error":
                    MessageBox.Show("Code: " + ex.StripeError.Code + " Message: " + ex.Message);
                    break;

                case "api_error":
                    MessageBox.Show("Code: " + ex.StripeError.Code + " Message: " + ex.Message);
                    break;

                case "authentication_error":
                    MessageBox.Show("Code: " + ex.StripeError.Code + " Message: " + ex.Message);
                    break;

                case "invalid_request_error":
                    MessageBox.Show("Code: " + ex.StripeError.Code + " Message: " + ex.Message);
                    break;

                case "rate_limit_error":
                    MessageBox.Show("Code: " + ex.StripeError.Code + " Message: " + ex.Message);
                    break;

                case "validation_error":
                    MessageBox.Show("Code: " + ex.StripeError.Code + " Message: " + ex.Message);
                    break;

                default:
                    // Unknown Error Type
                    MessageBox.Show("Code: " + ex.StripeError.Code + " Message: " + ex.Message);
                    break;
                }
            }
        }
Exemple #18
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);
        }
        public bool delete(string id, bool info)
        {
            try
            {
                string decryptedId    = protector.Unprotect(id);
                int    decryptedIntId = Convert.ToInt32(decryptedId);

                var order = context.Order.Include(x => x.Charges).Include(x => x.Cus_model).Include(x => x.Products).FirstOrDefault(x => x.order_id == decryptedIntId);
                if ((int)order.status >= 1 && info == false)
                {
                    return(false);
                }
                else
                {
                    if (order.status == Status.Completed)
                    {
                        var ProductsList = order.Products.Select(x => new Products()
                        {
                            Quantity = x.Quantity,
                            modelId  = x.modelId,
                            id       = x.id,
                            order_id = x.order_id,
                            price    = x.price
                        }).ToList();
                        bool result = util.updatequan(ProductsList, order.store_id, "Add");
                        if (!result)
                        {
                            return(false);
                        }
                    }
                }
                if (order.PaymentMethod == PaymentMethods.Stripe)
                {
                    var Service = new ChargeService();
                    var service = new RefundService();
                    foreach (var charge in order.Charges.OrderBy(x => x.priority))
                    {
                        try
                        {
                            var    charg  = Service.Get(charge.ChargeId);
                            double Amount = charg.Amount - charg.AmountRefunded;
                            Amount -= (2.9 / 100 * Amount);
                            var options = new RefundCreateOptions
                            {
                                Charge = charge.ChargeId,
                                Amount = Convert.ToInt64(Amount)
                            };
                            var refund = service.Create(options);
                            if (refund != null)
                            {
                                logger.LogCritical(Amount + "Refunded To " + order.Cus_model.CustRef + "Date" + DateTime.Now);
                            }
                        }
                        catch (Exception)
                        {
                            logger.LogError("Fail To Refund To " + order.Cus_model.CustRef + "Date" + DateTime.Now);
                            return(false);
                        }
                    }
                }
                context.Entry(order).State = EntityState.Deleted;
                context.SaveChanges();
                return(true);
            }
            catch (Exception e)
            {
                return(false);
            }
        }