Example #1
0
        public CapturePaymentResult Capture(CapturePaymentRequest capturePaymentRequest)
        {
            var result = new CapturePaymentResult();

            try
            {
                var stripeCharge = _chargeService.Capture(capturePaymentRequest.Order.AuthorizationTransactionId);

                result.NewPaymentStatus         = PaymentStatus.Paid;
                result.CaptureTransactionResult = stripeCharge.Status;
                result.CaptureTransactionId     = stripeCharge.Id;

                return(result);
            }
            catch (StripeException exception)
            {
                if (!string.IsNullOrEmpty(exception.StripeError.Code))
                {
                    result.AddError(exception.StripeError.Message + " Error code: " + exception.StripeError.Code);
                }
                else
                {
                    result.AddError(exception.StripeError.Message);
                }

                return(result);
            }
        }
Example #2
0
        private PaymentProcessingResult ProcessPaymentCapture(IOrderGroup orderGroup,
                                                              ICreditCardPayment creditCardPayment,
                                                              IOrderAddress billingAddress)
        {
            if (string.IsNullOrEmpty(creditCardPayment.ProviderPaymentId))
            {
                return(Charge(orderGroup, creditCardPayment, billingAddress));
            }
            try
            {
                var capture = _stripeChargeService.Capture(creditCardPayment.ProviderPaymentId, new StripeChargeCaptureOptions());
                if (!string.IsNullOrEmpty(capture.FailureCode))
                {
                    return(PaymentProcessingResult.CreateUnsuccessfulResult(Translate(capture.Outcome.Reason)));
                }
                creditCardPayment.ProviderPaymentId     = capture.Id;
                creditCardPayment.ProviderTransactionID = capture.BalanceTransactionId;
                return(PaymentProcessingResult.CreateSuccessfulResult(""));
            }
            catch (StripeException e)
            {
                switch (e.StripeError.ErrorType)
                {
                case "card_error":
                    return(PaymentProcessingResult.CreateUnsuccessfulResult(Translate(e.StripeError.Code)));

                default:
                    return(PaymentProcessingResult.CreateUnsuccessfulResult(e.StripeError.Message));
                }
            }
        }
Example #3
0
        public charges_fixture()
        {
            // make sure there's a charge
            Charge = Cache.GetStripeCharge(Cache.ApiKey);

            ChargeListOptions = new StripeChargeListOptions();

            var service = new StripeChargeService(Cache.ApiKey);

            Charges = service.List(ChargeListOptions);

            ChargeUpdateOptions = new StripeChargeUpdateOptions
            {
                Description = "updatd description",
                // setting the updated shipping object to the same object used for the create charge
                // i attempted to just create a new shipping object and set one property,
                // but it threw an error 'name' was not supplied (which was on the original)
                Shipping = Cache.GetStripeChargeCreateOptions().Shipping
            };

            ChargeUpdateOptions.Shipping.Phone          = "8675309";
            ChargeUpdateOptions.Shipping.TrackingNumber = "56789";

            UpdatedCharge = service.Update(Charge.Id, ChargeUpdateOptions);

            UncapturedCharge = Cache.GetStripeChargeUncaptured(Cache.ApiKey);

            ChargeCaptureOptions = new StripeChargeCaptureOptions
            {
                Amount = 123,
                StatementDescriptor = "CapturedCharge"
            };
            CapturedCharge = service.Capture(UncapturedCharge.Id, ChargeCaptureOptions);
        }
        public Transaction_Result Capture(AuthCapture_Details details)
        {
            bool isApproved = false;
            bool isPending  = false;

            try
            {
                StripeConfiguration.SetApiKey(secretKey);
                var          receivedTokenId = details.TransactionIndex;
                var          chargeOptions   = new StripeChargeCreateOptions();
                var          chargeService   = new StripeChargeService();
                StripeCharge charge          = new StripeCharge();
                charge.Captured = true;
                //charge = chargeService.Get(receivedTokenId);
                charge = chargeService.Capture(receivedTokenId);
                string status = charge.Status;
                if (status.Contains("succeeded"))
                {
                    isApproved = true;
                }
                else if (status.Contains("pending"))
                {
                    isPending = true;
                }
                return(new Transaction_Result
                {
                    isApproved = isApproved,
                    hasServerError = false,
                    isPending = isPending,
                    TransactionIndex = charge.BalanceTransactionId,
                    ProviderToken = charge.Id,
                    FullResponse = charge.StripeResponse.ResponseJson,
                    ApprovalCode = status,
                    ResultText = charge.Status
                });
            }
            catch (StripeException e)
            {
                //string errorMessage = handleStripeError(e);
                return(new Transaction_Result
                {
                    isApproved = false,
                    hasServerError = true,
                    ErrorText = e.StripeError.Message,
                    ErrorCode = e.StripeError.Code,
                    ProviderToken = null,
                    FullResponse = e.StripeError.StripeResponse.ResponseJson
                });
            }
        }
Example #5
0
        public bool OrderAction(int id, int status, out string message)
        {
            message = string.Empty;

            var order = _orderService.Find(id);

            // Get the latest successful transaction
            var transactionQuery = _transactionService.Query(x => x.OrderID == id && string.IsNullOrEmpty(x.FailureCode)).Select();
            var transaction      = transactionQuery.OrderByDescending(x => x.Created).FirstOrDefault();

            if (transaction == null)
            {
                message = "[[[Transaction not found]]]";
                return(false);
            }

            if (status == (int)Enum_OrderStatus.Cancelled)
            {
                // Update order
                order.Modified    = DateTime.Now;
                order.Status      = status;
                order.ObjectState = Repository.Pattern.Infrastructure.ObjectState.Modified;
                _orderService.Update(order);
            }
            else if (status == (int)Enum_OrderStatus.Confirmed)
            {
                // Update order
                order.Modified    = DateTime.Now;
                order.Status      = status;
                order.ObjectState = Repository.Pattern.Infrastructure.ObjectState.Modified;
                _orderService.Update(order);

                // Update Transaction
                transaction.IsCaptured  = true;
                transaction.LastUpdated = DateTime.Now;
                _transactionService.Update(transaction);

                // Capture payment
                var          chargeService = new StripeChargeService(CacheHelper.GetSettingDictionary(StripePlugin.SettingStripeApiKey).Value);
                StripeCharge stripeCharge  = chargeService.Capture(transaction.ChargeID);
            }

            _unitOfWorkAsync.SaveChanges();
            _unitOfWorkAsyncStripe.SaveChanges();

            return(true);
        }
Example #6
0
        public override ApiInfo CapturePayment(Order order, IDictionary <string, string> settings)
        {
            try {
                order.MustNotBeNull("order");
                settings.MustNotBeNull("settings");
                settings.MustContainKey("mode", "settings");
                settings.MustContainKey(settings["mode"] + "_secret_key", "settings");

                StripeChargeService chargeService = new StripeChargeService(settings[settings["mode"] + "_secret_key"]);
                StripeCharge        charge        = chargeService.Capture(order.TransactionInformation.TransactionId, (int)order.TransactionInformation.AmountAuthorized.Value * 100);

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

            return(null);
        }
Example #7
0
        private void CaptureCharge(Transaction t)
        {
            StripeConfiguration.SetApiKey(Settings.StripeApiKey);

            var chargeService = new StripeChargeService();

            var stripeCharge = chargeService.Capture(t.PreviousTransactionNumber, (int)(t.Amount * 100));

            if (stripeCharge.Id.Length > 0 && stripeCharge.Amount > 0)
            {
                t.Result.Succeeded       = true;
                t.Result.ReferenceNumber = stripeCharge.Id;
            }
            else
            {
                t.Result.Succeeded               = false;
                t.Result.ResponseCode            = "FAIL";
                t.Result.ResponseCodeDescription = "Stripe Failure";
            }
        }
        public int Add(AddSubscriptionBookingParams param)
        {
            try
            {
                using (var transaction = new TransactionScope())
                {
                    var bookingCode = Helper.RandomString(Constant.BookingCodeLength);
                    while (IsBookingCodeExists(bookingCode))
                    {
                        bookingCode = Helper.RandomString(Constant.BookingCodeLength);
                    }
                    param.SubscriptionBookingsObject.BookingCode = bookingCode;

                    // Insert New Bookings
                    DayaxeDbContext.SubscriptionBookings.InsertOnSubmit(param.SubscriptionBookingsObject);
                    Commit();

                    if (param.SubscriptionBookingDiscounts != null && param.SubscriptionBookingDiscounts.Id > 0)
                    {
                        var subscriptionDiscount = new SubscriptionBookingDiscounts
                        {
                            DiscountId            = param.SubscriptionBookingDiscounts.Id,
                            SubscriptionBookingId = param.SubscriptionBookingsObject.Id,
                            SubscriptionId        = param.SubscriptionBookingsObject.SubscriptionId
                        };

                        DayaxeDbContext.SubscriptionBookingDiscounts.InsertOnSubmit(subscriptionDiscount);
                    }

                    // Insert to History for First Cycle
                    var cycle = new SubscriptionCycles
                    {
                        SubscriptionBookingId = param.SubscriptionBookingsObject.Id,
                        StartDate             = param.SubscriptionBookingsObject.StartDate,
                        EndDate         = param.SubscriptionBookingsObject.EndDate,
                        CancelDate      = param.SubscriptionBookingsObject.CancelDate,
                        LastUpdatedBy   = param.SubscriptionBookingsObject.LastUpdatedBy,
                        LastUpdatedDate = param.SubscriptionBookingsObject.LastUpdatedDate,
                        Status          = param.SubscriptionBookingsObject.Status,
                        Price           = param.ActualPrice,
                        MerchantPrice   = param.MerchantPrice,
                        PayByCredit     = param.PayByCredit,
                        TotalPrice      = param.TotalPrice,
                        Quantity        = param.SubscriptionBookingsObject.Quantity,
                        StripeChargeId  = string.Empty,
                        StripeCouponId  = param.SubscriptionBookingsObject.StripeCouponId,
                        StripeInvoiceId = string.Empty,
                        CycleNumber     = 1
                    };

                    DayaxeDbContext.SubscriptionCycles.InsertOnSubmit(cycle);

                    // Insert Discount for Current Customer active Subscription
                    var discount = new Discounts
                    {
                        DiscountName = string.Format("{0} - {1} {2}",
                                                     param.SubscriptionName,
                                                     param.FirstName,
                                                     param.LastName),
                        Code          = string.Format("SUP{0}", Helper.RandomString(8)),
                        StartDate     = param.SubscriptionBookingsObject.StartDate,
                        EndDate       = param.SubscriptionBookingsObject.EndDate,
                        CodeRequired  = true,
                        PercentOff    = 100,
                        PromoType     = (byte)Enums.PromoType.SubscriptionPromo,
                        MinAmount     = 0,
                        IsAllProducts = true,
                        MaxPurchases  = (byte)param.MaxPurchases
                    };
                    DayaxeDbContext.Discounts.InsertOnSubmit(discount);
                    Commit();

                    // Add Invoices
                    var subscriptionInvoice = new SubscriptionInvoices
                    {
                        SubscriptionCyclesId = cycle.Id,
                        BookingStatus        = cycle.Status,
                        Quantity             = cycle.Quantity,
                        Price              = cycle.Price,
                        MerchantPrice      = cycle.MerchantPrice,
                        PayByCredit        = cycle.PayByCredit,
                        TotalPrice         = cycle.TotalPrice,
                        InvoiceStatus      = (int)Enums.InvoiceStatus.Charge,
                        StripeChargeId     = cycle.StripeChargeId,
                        ChargeAmount       = cycle.Price,
                        StripeRefundId     = string.Empty,
                        RefundAmount       = 0,
                        RefundCreditAmount = 0,
                        StripeCouponId     = cycle.StripeCouponId,
                        CreatedDate        = DateTime.UtcNow,
                        CreatedBy          = 1
                    };
                    DayaxeDbContext.SubscriptionInvoices.InsertOnSubmit(subscriptionInvoice);

                    var discountUsed = new SubsciptionDiscountUseds
                    {
                        CustomerId            = param.SubscriptionBookingsObject.CustomerId,
                        DiscountId            = discount.Id,
                        SubscriptionBookingId = param.SubscriptionBookingsObject.Id
                    };
                    DayaxeDbContext.SubsciptionDiscountUseds.InsertOnSubmit(discountUsed);

                    var cusCredits = DayaxeDbContext.CustomerCredits
                                     .SingleOrDefault(cc => cc.CustomerId == param.CustomerCreditsObject.CustomerId);

                    // Add Logs when refund by Upgrade to Subscription
                    if (param.RefundCreditByUpgrade > 0)
                    {
                        var creditLogs = new CustomerCreditLogs
                        {
                            Amount                = param.RefundCreditByUpgrade,
                            ProductId             = 0,
                            BookingId             = 0,
                            SubscriptionId        = param.SubscriptionBookingsObject.SubscriptionId,
                            CreatedBy             = param.CustomerCreditsObject.CustomerId,
                            CreatedDate           = DateTime.UtcNow,
                            CreditType            = (byte)Enums.CreditType.PartialPuchaseRefund,
                            Description           = param.RefundCreditDescription,
                            CustomerId            = param.CustomerCreditsObject.CustomerId,
                            ReferralId            = param.CustomerCreditsObject.ReferralCustomerId,
                            SubscriptionBookingId = param.SubscriptionBookingsObject.Id,
                            Status                = true,
                            GiftCardId            = 0
                        };

                        DayaxeDbContext.CustomerCreditLogs.InsertOnSubmit(creditLogs);

                        if (cusCredits != null)
                        {
                            cusCredits.Amount += param.RefundCreditByUpgrade;
                        }
                    }

                    // Add Logs when pay by DayAxe Credit
                    if (param.PayByCredit > 0)
                    {
                        var creditLogs = new CustomerCreditLogs
                        {
                            Amount                = param.PayByCredit,
                            ProductId             = 0,
                            BookingId             = 0,
                            SubscriptionId        = param.SubscriptionBookingsObject.SubscriptionId,
                            CreatedBy             = param.CustomerCreditsObject.CustomerId,
                            CreatedDate           = DateTime.UtcNow,
                            CreditType            = (byte)Enums.CreditType.Charge,
                            Description           = param.Description,
                            CustomerId            = param.CustomerCreditsObject.CustomerId,
                            ReferralId            = param.CustomerCreditsObject.ReferralCustomerId,
                            SubscriptionBookingId = param.SubscriptionBookingsObject.Id,
                            Status                = true,
                            GiftCardId            = 0
                        };

                        DayaxeDbContext.CustomerCreditLogs.InsertOnSubmit(creditLogs);

                        if (cusCredits != null)
                        {
                            cusCredits.Amount -= param.PayByCredit;
                        }
                    }

                    // First Buy of referral
                    if (param.CustomerCreditsObject != null && param.CustomerCreditsObject.ReferralCustomerId > 0 && (
                            DayaxeDbContext.Bookings.Count(x => x.CustomerId == param.SubscriptionBookingsObject.CustomerId) == 1 ||
                            DayaxeDbContext.SubscriptionBookings.Count(x => x.CustomerId == param.SubscriptionBookingsObject.CustomerId) == 1))
                    {
                        var logs = DayaxeDbContext.CustomerCreditLogs
                                   .Where(ccl => ccl.CustomerId == param.CustomerCreditsObject.ReferralCustomerId &&
                                          ccl.ReferralId == param.SubscriptionBookingsObject.CustomerId &&
                                          !ccl.Status)
                                   .ToList();

                        if (logs.Any())
                        {
                            logs.ForEach(log =>
                            {
                                var cus = DayaxeDbContext.CustomerCredits
                                          .FirstOrDefault(cc => cc.CustomerId == log.CustomerId);
                                if (cus != null)
                                {
                                    cus.Amount += log.Amount;
                                }

                                log.Status = true;
                            });
                            Commit();
                        }
                    }

                    // Add to Customer Credit Log
                    var logsReferred = DayaxeDbContext.CustomerCreditLogs
                                       .Where(ccl => ccl.ReferralId == param.SubscriptionBookingsObject.CustomerId && !ccl.Status)
                                       .ToList();
                    if (logsReferred.Any())
                    {
                        logsReferred.ForEach(log =>
                        {
                            var cus = DayaxeDbContext.CustomerCredits
                                      .FirstOrDefault(cc => cc.CustomerId == log.CustomerId);
                            if (cus != null)
                            {
                                cus.Amount += log.Amount;
                            }

                            log.Status = true;
                        });
                    }

                    // Insert Schedule
                    var schedules = new Schedules
                    {
                        ScheduleSendType      = (int)Enums.ScheduleSendType.IsEmailConfirmSubscription,
                        Name                  = "Send Email confirm Subscription",
                        Status                = (int)Enums.ScheduleType.NotRun,
                        SubscriptionBookingId = param.SubscriptionBookingsObject.Id
                    };
                    DayaxeDbContext.Schedules.InsertOnSubmit(schedules);

                    // Maybe not use here because flow upgrade to subscription do not use this
                    if (param.BookingId > 0)
                    {
                        var bookings = DayaxeDbContext.Bookings.FirstOrDefault(b => b.BookingId == param.BookingId);
                        if (bookings != null)
                        {
                            var chargePrice = (int)((bookings.TotalPrice - bookings.HotelPrice) * 100);
                            try
                            {
                                bookings.TotalPrice -= bookings.HotelPrice;
                                bookings.PassStatus  = (int)Enums.BookingStatus.Active;

                                var discounts = new DiscountBookings
                                {
                                    DiscountId = discount.Id,
                                    ProductId  = bookings.ProductId,
                                    BookingId  = bookings.BookingId
                                };

                                DayaxeDbContext.DiscountBookings.InsertOnSubmit(discounts);
                                bookings.IsActiveSubscription = true;

                                string responseString;
                                if (chargePrice > 0)
                                {
                                    var          chargeService = new StripeChargeService();
                                    StripeCharge charge        = chargeService.Capture(bookings.StripeChargeId, chargePrice);
                                    responseString = charge.StripeResponse.ResponseJson;
                                }
                                else
                                {
                                    var refundOptions = new StripeRefundCreateOptions
                                    {
                                        Reason = StripeRefundReasons.RequestedByCustomer
                                    };
                                    var          refundService = new StripeRefundService();
                                    StripeRefund refund        = refundService.Create(bookings.StripeChargeId, refundOptions);
                                    responseString = refund.StripeResponse.ResponseJson;
                                }

                                var logs = new Logs
                                {
                                    LogKey         = "UpgradeSubscriptionCharge",
                                    UpdatedContent = string.Format("Params: {0} - Response: {1}",
                                                                   JsonConvert.SerializeObject(param, CustomSettings.SerializerSettings()),
                                                                   responseString),
                                    UpdatedBy   = param.SubscriptionBookingsObject.CustomerId,
                                    UpdatedDate = DateTime.UtcNow
                                };
                                AddLog(logs);
                            }
                            catch (Exception ex)
                            {
                                var logs = new Logs
                                {
                                    LogKey         = "UpgradeSubscriptionChargeError",
                                    UpdatedContent = string.Format("Params: {0} - {1} - {2} - {3}",
                                                                   JsonConvert.SerializeObject(param, CustomSettings.SerializerSettings()),
                                                                   ex.Message,
                                                                   ex.StackTrace,
                                                                   ex.Source),
                                    UpdatedBy   = param.SubscriptionBookingsObject.CustomerId,
                                    UpdatedDate = DateTime.UtcNow
                                };
                                AddLog(logs);
                            }
                        }
                    }

                    Commit();

                    transaction.Complete();
                }
            }
            catch (Exception ex)
            {
                var logs = new Logs
                {
                    LogKey         = "AddBookingError",
                    UpdatedContent = string.Format("{0} - {1} - {2} - {3}", param.SubscriptionBookingsObject.CustomerId, ex.Message, ex.StackTrace, ex.Source),
                    UpdatedBy      = param.SubscriptionBookingsObject.CustomerId,
                    UpdatedDate    = DateTime.UtcNow
                };
                AddLog(logs);

                throw new Exception(ex.Message, ex);
            }

            return(param.SubscriptionBookingsObject.Id);
        }
Example #9
0
        public charges_fixture()
        {
            // make sure there's a charge
            Charge = Cache.GetStripeCharge(Cache.ApiKey);

            ChargeListOptions = new StripeChargeListOptions();

            var service = new StripeChargeService(Cache.ApiKey);

            Charges = service.List(ChargeListOptions);

            ChargeUpdateOptions = new StripeChargeUpdateOptions
            {
                Description = "updatd description",
                // setting the updated shipping object to the same object used for the create charge
                // i attempted to just create a new shipping object and set one property,
                // but it threw an error 'name' was not supplied (which was on the original)
                Shipping = Cache.GetStripeChargeCreateOptions().Shipping
            };

            ChargeUpdateOptions.Shipping.Phone          = "8675309";
            ChargeUpdateOptions.Shipping.TrackingNumber = "56789";

            UpdatedCharge = service.Update(Charge.Id, ChargeUpdateOptions);

            UncapturedCharge = Cache.GetStripeChargeUncaptured(Cache.ApiKey);

            ChargeCaptureOptions = new StripeChargeCaptureOptions
            {
                Amount = 123,
                StatementDescriptor = "CapturedCharge"
            };
            CapturedCharge = service.Capture(UncapturedCharge.Id, ChargeCaptureOptions);

            // Create a charge with Level 3 data
            var chargeLevel3Options = Cache.GetStripeChargeCreateOptions();

            chargeLevel3Options.Amount = 11700;
            chargeLevel3Options.Level3 = new StripeChargeLevel3Options
            {
                CustomerReference  = "customer 1",
                MerchantReference  = "1234",
                ShippingFromZip    = "90210",
                ShippingAddressZip = "94110",
                ShippingAmount     = 700,
                LineItems          = new List <StripeChargeLevel3LineItemOptions>
                {
                    new StripeChargeLevel3LineItemOptions
                    {
                        DiscountAmount     = 200,
                        ProductCode        = "1234",
                        ProductDescription = "description 1",
                        Quantity           = 2,
                        TaxAmount          = 200,
                        UnitCost           = 1000,
                    },
                    new StripeChargeLevel3LineItemOptions
                    {
                        DiscountAmount     = 300,
                        ProductCode        = "1235",
                        ProductDescription = "description 2",
                        Quantity           = 3,
                        TaxAmount          = 300,
                        UnitCost           = 3000,
                    },
                },
            };
            Level3Charge = service.Create(chargeLevel3Options);
        }