public RefundPaymentResult Refund(RefundPaymentRequest refundPaymentRequest) { var result = new RefundPaymentResult(); try { var options = new StripeRefundCreateOptions(); var charge = _chargeService.Get(refundPaymentRequest.Order.CaptureTransactionId); var maximumRefund = charge.Amount - charge.AmountRefunded; options.Amount = (int)Math.Ceiling(refundPaymentRequest.AmountToRefund * 100); if (maximumRefund == 0 && !refundPaymentRequest.IsPartialRefund) //if it's a partial refund the user would not expect to see the order switch to the Refund status { result.NewPaymentStatus = PaymentStatus.Refunded; // this means it has been previously refunded from Stripe admin return(result); } if (options.Amount > maximumRefund) { if (maximumRefund > 0) { result.AddError("This charge has already been partially refunded. Maximum refund amount is: " + (decimal)maximumRefund / 100); } else { result.AddError("This charge has already been fully refunded."); } return(result); } refundPaymentRequest.IsPartialRefund = options.Amount != maximumRefund; _refundService.Create(refundPaymentRequest.Order.CaptureTransactionId, options); result.NewPaymentStatus = refundPaymentRequest.IsPartialRefund ? PaymentStatus.PartiallyRefunded : PaymentStatus.Refunded; 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); } }
public RefundResponse Refund(RefundRequest request) { var refundService = new StripeRefundService(); var result = _refundResponseCreator.CreateResponse(refundService.Create(request.ChargeId, _refundRequestCreator.CreateRequest(request))); return(result); }
public static string RefundToUser(string chargeId, bool isFullRefund, int specificAmount) { try { string stripekey = ConfigurationManager.AppSettings["AdminStripeApiKey"]; StripeConfiguration.SetApiKey(stripekey); StripeRefundCreateOptions refundOptions; if (isFullRefund == true) { refundOptions = new StripeRefundCreateOptions() { Reason = StripeRefundReasons.RequestedByCustomer, //RefundApplicationFee = true }; } else { refundOptions = new StripeRefundCreateOptions() { Reason = StripeRefundReasons.RequestedByCustomer, //RefundApplicationFee = true, Amount = specificAmount * 100 }; } var refundService = new StripeRefundService(); StripeRefund refund = refundService.Create(chargeId, refundOptions); return(refund.Id); } catch (Exception ex) { Common.ExcepLog(ex); return(null); } }
public void Refund(string paymentId, int amount) { var chargeService = new StripeRefundService(); new StripeRefundCreateOptions().Amount = amount; chargeService.Create(paymentId); }
public async Task <StripeRefund> RefundChargeAsync(string chargeId, StripeRefundCreateOptions options, string apiKey) { var refundService = new StripeRefundService(apiKey); var refund = refundService.Create(chargeId, options); return(refund); }
private StripeRefund CallStripeRefund(string stripeChargeId, double diffPrice) { var refundService = new StripeRefundService(); StripeRefund refund = refundService.Create(stripeChargeId, new StripeRefundCreateOptions() { Amount = Convert.ToInt32(diffPrice * 100), Reason = StripeRefundReasons.RequestedByCustomer }); return(refund); }
private StripeRefund CreateStripeRefund(long Amount, string ChargeID) { var refundOptions = new StripeRefundCreateOptions() { Amount = (int)Amount, Reason = StripeRefundReasons.Unknown }; var refundService = new StripeRefundService(); return(refundService.Create(ChargeID, refundOptions)); }
public static StripeRefund RefundCharge(string chargeId) { try { var refundService = new StripeRefundService(); StripeRefund refund = refundService.Create(chargeId); return(refund); } catch (Exception ex) { var exp = ex.Message.ToString(); return(null); } }
public static StripeRefund RefundCharge(string token, int amount) { // 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(MasterStrings.StripeSecretKey); var refundOptions = new StripeRefundCreateOptions() { Amount = amount, Reason = "requested_by_customer" }; var refundService = new StripeRefundService(); StripeRefund refund = refundService.Create(token, refundOptions); return(refund); }
private PaymentProcessingResult ProcessPaymentRefund(IOrderGroup orderGroup, ICreditCardPayment creditCardPayment) { var refundAmount = creditCardPayment.Amount; var purchaseOrder = (IPurchaseOrder)orderGroup; if (purchaseOrder == null || refundAmount <= 0 || string.IsNullOrEmpty(creditCardPayment.ProviderPaymentId)) { return(PaymentProcessingResult.CreateUnsuccessfulResult(Translate("RefundError"))); } try { var refundOptions = new StripeRefundCreateOptions() { Amount = (int)refundAmount * GetMultiplier(orderGroup.Currency), Reason = StripeRefundReasons.RequestedByCustomer }; var refund = _stripeRefundService.Create(creditCardPayment.ProviderPaymentId, refundOptions); // Extract the response details. creditCardPayment.TransactionID = refund.Id; var message = $"[{creditCardPayment.PaymentMethodName}] [RefundTransaction-{refund.Id}] " + $"Response: {refund.Status} at Timestamp={refund.Created.ToString()}: {refund.Amount}{refund.Currency}"; // add a new order note about this refund AddNoteToPurchaseOrder("REFUND", message, purchaseOrder.CustomerId, purchaseOrder); _orderRepository.Service.Save(purchaseOrder); return(PaymentProcessingResult.CreateSuccessfulResult(message)); } catch (StripeException e) { switch (e.StripeError.ErrorType) { case "card_error": return(PaymentProcessingResult.CreateUnsuccessfulResult(Translate(e.StripeError.Code))); default: return(PaymentProcessingResult.CreateUnsuccessfulResult(e.StripeError.Message)); } } }
public RefundPaymentResult Refund(RefundPaymentRequest refundPaymentRequest) { var stripeCharge = _chargeEntityService.Get(refundPaymentRequest.Order.OrderGuid); var customerDomainModel = _customerEntityService.GetOrCreate(stripeCharge.SellerCustomerId); var requestOptions = new StripeRequestOptions(); requestOptions.StripeConnectAccountId = customerDomainModel.StripeUserId; var refund = _stripeRefundService.Create(stripeCharge.StripeChargeId, requestOptions: requestOptions); var result = new RefundPaymentResult(); if (refund.Status == "succeeded") { result.NewPaymentStatus = Core.Domain.Payments.PaymentStatus.Refunded; } else { result.AddError("Error " + refund.FailureReason); } return(result); }
private void CreateRefund(Transaction t) { StripeConfiguration.SetApiKey(Settings.StripeApiKey); var refundService = new StripeRefundService(); var refundOptions = new StripeRefundCreateOptions(); refundOptions.Amount = (int)(t.Amount * 100); var refund = refundService.Create(t.PreviousTransactionNumber, refundOptions); if (refund.Id.Length > 0) { t.Result.Succeeded = true; t.Result.ReferenceNumber = refund.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); }
public HttpResponseMessage ProcessTransaction(IncomingProcessTransaction model) { return(ErrorFactory.Handle(() => { var userId = User?.Identity?.GetUserId(); if (string.IsNullOrWhiteSpace(userId)) { throw new Exception(); } var context = new PoolReservationEntities(); using (var unitOfWork = new UnitOfWork(context)) { PrepareAndGetReservationForProcessing_Result reservation = null; try { reservation = context.PrepareAndGetReservationForProcessing(model.ReservationId)?.FirstOrDefault(); } catch (Exception) { context.ChangeProcessingStatusToPending(model.ReservationId); } if (reservation == null) { try { context.ChangeProcessingStatusToPending(model.ReservationId); } catch (Exception) { } return JsonFactory.CreateJsonMessage(null, HttpStatusCode.NotFound, this.Request); } if (reservation.StatusId != Convert.ToInt32(ReservationGroupStatusEnum.PROCESSING)) { try { context.ChangeProcessingStatusToPending(model.ReservationId); } catch (Exception) { } return JsonFactory.CreateJsonMessage(new OutgoingMessage { Action = "wrongStatus" }, HttpStatusCode.NotFound, this.Request); } ReservationGroup reservationDBObject = null; try { reservationDBObject = unitOfWork.Reservations.GetReservationWithItems(userId, model.ReservationId); if (reservationDBObject == null) { return JsonFactory.CreateJsonMessage(null, HttpStatusCode.NotFound, this.Request); } } catch (Exception) { context.ChangeProcessingStatusToPending(model.ReservationId); } if (reservationDBObject.StatusId != Convert.ToInt32(ReservationGroupStatusEnum.PROCESSING)) { try { context.ChangeProcessingStatusToPending(model.ReservationId); } catch (Exception) { } return JsonFactory.CreateJsonMessage(new OutgoingMessage { Action = "wrongStatus" }, HttpStatusCode.NotFound, this.Request); } ReservationTransaction resTransaction = null; int stripeModifiedPriceInCents = 0; try { decimal priceToCharge = 0M; foreach (var item in reservationDBObject.ReserveItems) { if (item.IsDeleted == true) { continue; } priceToCharge += item.FinalPrice; } decimal stripeModifiedPrice = priceToCharge * 100.0M; stripeModifiedPriceInCents = (int)Math.Round(stripeModifiedPrice); //Must Update Repo If Changed. Rounds to the nearest penny. if (stripeModifiedPriceInCents <= 50) { return JsonFactory.CreateJsonMessage(new OutgoingMessage { Action = "noPriceToCharge" }, HttpStatusCode.NotFound, this.Request); } resTransaction = unitOfWork.Reservations.AddStripeChargeToPendingReservation(userId, userId, model.ReservationId, model.StripeTokenId, priceToCharge); unitOfWork.Complete(); } catch (Exception e) { context.ChangeProcessingStatusToPending(model.ReservationId); } string chargeId = null; try { if (resTransaction == null) { throw new Exception(); } var myCharge = new StripeChargeCreateOptions(); // always set these properties myCharge.Amount = stripeModifiedPriceInCents; myCharge.Currency = "usd"; // set this if you want to myCharge.Description = "JustMosey Reservation"; myCharge.SourceTokenOrExistingSourceId = model.StripeTokenId; // (not required) set this to false if you don't want to capture the charge yet - requires you call capture later myCharge.Capture = true; var chargeService = new StripeChargeService(); StripeCharge stripeCharge = chargeService.Create(myCharge); chargeId = stripeCharge.Id; unitOfWork.Reservations.UpdateStripeSuccessfulChargeOnPendingReservation(userId, userId, resTransaction.Id, chargeId); unitOfWork.Complete(); } catch (Exception e) { try { var refundService = new StripeRefundService(); StripeRefund refund = refundService.Create(chargeId, new StripeRefundCreateOptions() { Amount = stripeModifiedPriceInCents, Reason = StripeRefundReasons.Unknown }); } catch (Exception) { } try { unitOfWork.Reservations.RefundStripeSuccessfulChargeOnPendingReservation(userId, userId, resTransaction.Id); unitOfWork.Complete(); } catch (Exception) { } try { } catch (Exception) { context.ChangeProcessingStatusToPending(model.ReservationId); } return JsonFactory.CreateJsonMessage(new OutgoingMessage { Action = "unknownErrorAfterProcessing" }, HttpStatusCode.InternalServerError, this.Request); } try { var updatedReservationDBObject = unitOfWork.Reservations.GetReservationWithItems(userId, model.ReservationId); var outgoingRes = OutgoingReservationGroup.Parse(updatedReservationDBObject); return JsonFactory.CreateJsonMessage(outgoingRes, HttpStatusCode.OK, this.Request); } catch (Exception) { return JsonFactory.CreateJsonMessage(null, HttpStatusCode.OK, this.Request); } } }, this.Request)); }