public static IPayment PaymentForInserting(Guid paymentMethodKey, PaymentMethodType paymentMethodType, decimal amount, Guid? customerKey = null) { var payment = new Payment(paymentMethodType, amount, paymentMethodKey) { CustomerKey = customerKey }; return payment; }
public FareAttribute(CSVRowItem item) { mFareID = item.ValidateNotEmptyOrNull("fare_id"); mPrice = decimal.Parse(item["price"]); mCurrencyType = item.ValidateNotEmptyOrNull("currency_type"); mPaymentMethod = item["payment_method"].ToPaymentMethodType(); mTransfers = item["transfers"].ToTransferType(); int tDur; mTransferDuration = int.TryParse(item["transfer_duration"], out tDur) ? tDur : (int?)null; }
private void ExecuteFactory(PaymentMethodType methodType) { PaymentMethodFactory factory = null; if (methodType == PaymentMethodType.CashOnDelivery) { factory = new CodPaymentMethod(); } else if (methodType == PaymentMethodType.GooglePay) { factory = new GooglePayPaymentMethod(); } else if (methodType == PaymentMethodType.NetBanking) { factory = new NetBankingPaymentMethod(); } else if (methodType == PaymentMethodType.PhonePay) { factory = new PhonePayPaymentMethod(); } Assert.AreEqual(expected: string.Format(expectedOutput, methodType), actual: factory.GetPaymentMethodType()); }
public async Task IapCheckAsync(User user, PaymentMethodType paymentMethodType) { if (paymentMethodType != PaymentMethodType.AppleInApp) { throw new BadRequestException("Payment method not supported for in-app purchases."); } if (user.Premium) { throw new BadRequestException("Already a premium user."); } if (!string.IsNullOrWhiteSpace(user.GatewayCustomerId)) { var customerService = new Stripe.CustomerService(); var customer = await customerService.GetAsync(user.GatewayCustomerId); if (customer != null && customer.Balance != 0) { throw new BadRequestException("Customer balance cannot exist when using in-app purchases."); } } }
internal Payment(PaymentMethodType paymentMethodType, decimal amount, Guid?paymentMethodKey, ExtendedDataCollection extendedData) : this(EnumTypeFieldConverter.PaymentMethod.GetTypeField(paymentMethodType).TypeKey, amount, paymentMethodKey, extendedData) { }
/// <summary> /// Creates and saves a payment /// </summary> /// <param name="paymentMethodType">The type of the payment method</param> /// <param name="amount">The amount of the payment</param> /// <param name="paymentMethodKey">The optional payment Method Key</param> /// <param name="raiseEvents">Optional boolean indicating whether or not to raise events</param> /// <returns>Returns <see cref="IPayment"/></returns> public IPayment CreatePaymentWithKey(PaymentMethodType paymentMethodType, decimal amount, Guid? paymentMethodKey, bool raiseEvents = true) { return CreatePaymentWithKey(EnumTypeFieldConverter.PaymentMethod.GetTypeField(paymentMethodType).TypeKey, amount, paymentMethodKey); }
internal Payment(PaymentMethodType paymentMethodType, decimal amount) : this(paymentMethodType, amount, null, new ExtendedDataCollection()) { }
internal TerminalBuilder(TransactionType type, PaymentMethodType paymentType) : base(type, null) { PaymentMethodType = paymentType; }
internal TerminalAuthBuilder(TransactionType type, PaymentMethodType paymentType) : base(type, paymentType) { }
/// <summary> /// Creates and saves a payment /// </summary> /// <param name="paymentMethodType">The type of the paymentmethod</param> /// <param name="amount">The amount of the payment</param> /// <param name="paymentMethodKey">The optional paymentMethodKey</param> /// <returns>Returns <see cref="IPayment"/></returns> public IPayment CreatePaymentWithKey(PaymentMethodType paymentMethodType, decimal amount, Guid? paymentMethodKey) { return _paymentService.CreatePaymentWithKey(paymentMethodType, amount, paymentMethodKey); }
public async Task PurchaseOrganizationAsync(Organization org, PaymentMethodType paymentMethodType, string paymentToken, Models.StaticStore.Plan plan, short additionalStorageGb, short additionalSeats, bool premiumAccessAddon) { var invoiceService = new InvoiceService(); var customerService = new CustomerService(); Braintree.Customer braintreeCustomer = null; string stipeCustomerSourceToken = null; var stripeCustomerMetadata = new Dictionary <string, string>(); var stripePaymentMethod = paymentMethodType == PaymentMethodType.Card || paymentMethodType == PaymentMethodType.BankAccount; if (stripePaymentMethod) { stipeCustomerSourceToken = paymentToken; } else if (paymentMethodType == PaymentMethodType.PayPal) { var randomSuffix = Utilities.CoreHelpers.RandomString(3, upper: false, numeric: false); var customerResult = await _btGateway.Customer.CreateAsync(new Braintree.CustomerRequest { PaymentMethodNonce = paymentToken, Email = org.BillingEmail, Id = org.BraintreeCustomerIdPrefix() + org.Id.ToString("N").ToLower() + randomSuffix, CustomFields = new Dictionary <string, string> { [org.BraintreeIdField()] = org.Id.ToString() } }); if (!customerResult.IsSuccess() || customerResult.Target.PaymentMethods.Length == 0) { throw new GatewayException("Failed to create PayPal customer record."); } braintreeCustomer = customerResult.Target; stripeCustomerMetadata.Add("btCustomerId", braintreeCustomer.Id); } else { throw new GatewayException("Payment method is not supported at this time."); } var subCreateOptions = new SubscriptionCreateOptions { TrialPeriodDays = plan.TrialPeriodDays, Items = new List <SubscriptionItemOption>(), Metadata = new Dictionary <string, string> { [org.GatewayIdField()] = org.Id.ToString() } }; if (plan.StripePlanId != null) { subCreateOptions.Items.Add(new SubscriptionItemOption { PlanId = plan.StripePlanId, Quantity = 1 }); } if (additionalSeats > 0 && plan.StripeSeatPlanId != null) { subCreateOptions.Items.Add(new SubscriptionItemOption { PlanId = plan.StripeSeatPlanId, Quantity = additionalSeats }); } if (additionalStorageGb > 0) { subCreateOptions.Items.Add(new SubscriptionItemOption { PlanId = plan.StripeStoragePlanId, Quantity = additionalStorageGb }); } if (premiumAccessAddon && plan.StripePremiumAccessPlanId != null) { subCreateOptions.Items.Add(new SubscriptionItemOption { PlanId = plan.StripePremiumAccessPlanId, Quantity = 1 }); } Customer customer = null; Subscription subscription = null; try { customer = await customerService.CreateAsync(new CustomerCreateOptions { Description = org.BusinessName, Email = org.BillingEmail, SourceToken = stipeCustomerSourceToken, Metadata = stripeCustomerMetadata }); subCreateOptions.CustomerId = customer.Id; var subscriptionService = new SubscriptionService(); subscription = await subscriptionService.CreateAsync(subCreateOptions); } catch (Exception e) { if (customer != null) { await customerService.DeleteAsync(customer.Id); } if (braintreeCustomer != null) { await _btGateway.Customer.DeleteAsync(braintreeCustomer.Id); } throw e; } org.Gateway = GatewayType.Stripe; org.GatewayCustomerId = customer.Id; org.GatewaySubscriptionId = subscription.Id; org.ExpirationDate = subscription.CurrentPeriodEnd; }
public PaymentMethod(PaymentMethodType type, User user) { this.Type = type; this.User = user; }
public PaymentMethod(PaymentMethodType type, User user, BankAccount bankAccount) : this(type, user) { BankAccount = bankAccount; }
/// <summary> /// Load active payment methods /// </summary> /// <param name="customer">Filter payment methods by customer and apply payment method restrictions; null to load all records</param> /// <param name="cart">Filter payment methods by cart amount; null to load all records</param> /// <param name="storeId">Filter payment methods by store identifier; pass 0 to load all records</param> /// <param name="types">Filter payment methods by payment method types</param> /// <param name="provideFallbackMethod">Provide a fallback payment method if none is active</param> /// <returns>Payment methods</returns> public virtual IEnumerable<Provider<IPaymentMethod>> LoadActivePaymentMethods( Customer customer = null, IList<OrganizedShoppingCartItem> cart = null, int storeId = 0, PaymentMethodType[] types = null, bool provideFallbackMethod = true) { IList<IPaymentMethodFilter> allFilters = null; IEnumerable<Provider<IPaymentMethod>> allProviders = null; var filterRequest = new PaymentFilterRequest { Cart = cart, StoreId = storeId, Customer = customer }; if (types != null && types.Any()) allProviders = LoadAllPaymentMethods(storeId).Where(x => types.Contains(x.Value.PaymentMethodType)); else allProviders = LoadAllPaymentMethods(storeId); var activeProviders = allProviders .Where(p => { if (!p.Value.IsActive || !_paymentSettings.ActivePaymentMethodSystemNames.Contains(p.Metadata.SystemName, StringComparer.InvariantCultureIgnoreCase)) return false; // payment method filtering if (allFilters == null) allFilters = GetAllPaymentMethodFilters(); filterRequest.PaymentMethod = p; if (allFilters.Any(x => x.IsExcluded(filterRequest))) return false; return true; }); if (!activeProviders.Any() && provideFallbackMethod) { var fallbackMethod = allProviders.FirstOrDefault(x => x.IsPaymentMethodActive(_paymentSettings)); if (fallbackMethod == null) fallbackMethod = allProviders.FirstOrDefault(); if (fallbackMethod != null) { return new Provider<IPaymentMethod>[] { fallbackMethod }; } else { if (DataSettings.DatabaseIsInstalled()) throw new SmartException(T("Payment.OneActiveMethodProviderRequired")); } } return activeProviders; }
public static bool Supports(this IPaymentProcessorPlugin paymentProcessorPlugin, PaymentMethodType methodType) { return(paymentProcessorPlugin.SupportedMethodTypes.Contains(methodType)); }
public IDeviceResponse StartCard(PaymentMethodType paymentMethodType) { return(_controller.SendMessage <SipBaseResponse>(string.Format("<SIP><Version>1.0</Version><ECRId>1004</ECRId><Request>StartCard</Request><RequestId>{0}</RequestId><CardGroup>{1}</CardGroup></SIP>", _requestIdProvider.GetRequestId(), paymentMethodType), HPA_MSG_ID.STARTCARD)); }
public void ReportDataCollect(TransactionType transactionType, PaymentMethodType paymentMethodType, decimal amount, string encodedRequest) { lock (objectLock) { TotalTransactionCount += 1; encodedRequests.Add(encodedRequest); switch (transactionType) { case TransactionType.Capture: case TransactionType.Sale: { if (paymentMethodType.Equals(PaymentMethodType.Credit)) { CardType = "CT "; CreditCardTransactionCount += 1; CreditCardTransactionSales += amount; } else if (paymentMethodType.Equals(PaymentMethodType.Debit) || paymentMethodType.Equals(PaymentMethodType.EBT)) { CardType = "DB "; DebitEBTTransactionCount += 1; DebitEBTTransactionSales += amount; } else { CardType = "OH "; OtherCardTransactionCount += 1; OtherCardTransactionSales += amount; } } break; case TransactionType.Reversal: { if (paymentMethodType.Equals(PaymentMethodType.Credit)) { CardType = "CT "; CreditCardTransactionCount += 1; CreditCardTransactionSales -= amount; } else if (paymentMethodType.Equals(PaymentMethodType.Debit) || paymentMethodType.Equals(PaymentMethodType.EBT)) { CardType = "DB "; DebitEBTTransactionCount += 1; DebitEBTTransactionSales -= amount; } else { CardType = "OH "; OtherCardTransactionCount += 1; OtherCardTransactionSales -= amount; } } break; case TransactionType.Refund: { if (paymentMethodType.Equals(PaymentMethodType.Credit)) { CardType = "CT "; CreditReturnTransactionCount += 1; CreditReturnTransactionSales += amount; } else if (paymentMethodType.Equals(PaymentMethodType.Debit) || paymentMethodType.Equals(PaymentMethodType.EBT)) { CardType = "DB "; DebitReturnTransactionCount += 1; DebitReturnTransactionSales += amount; } } break; case TransactionType.Void: { if (paymentMethodType.Equals(PaymentMethodType.Credit)) { CardType = "CT "; CreditVoidTransactionCount += 1; CreditVoidTransactionSales += amount; CreditCardTransactionSales -= amount; } else if (paymentMethodType.Equals(PaymentMethodType.Debit) || paymentMethodType.Equals(PaymentMethodType.EBT)) { CardType = "DB "; DebitEBTVoidTransactionCount += 1; DebitEBTVoidTransactionSales += amount; } } break; } Save(); } }
public override async Task MapAsync(IEnumerable <OrganizedShoppingCartItem> from, ShoppingCartModel to, dynamic parameters = null) { Guard.NotNull(from, nameof(from)); Guard.NotNull(to, nameof(to)); if (!from.Any()) { return; } await base.MapAsync(from, to, null); var store = _services.StoreContext.CurrentStore; var customer = _services.WorkContext.CurrentCustomer; var currency = _services.WorkContext.WorkingCurrency; var isEditable = parameters?.IsEditable == true; var validateCheckoutAttributes = parameters?.ValidateCheckoutAttributes == true; var prepareEstimateShippingIfEnabled = parameters?.PrepareEstimateShippingIfEnabled == true; var setEstimateShippingDefaultAddress = parameters?.SetEstimateShippingDefaultAddress == true; var prepareAndDisplayOrderReviewData = parameters?.PrepareAndDisplayOrderReviewData == true; #region Simple properties to.MediaDimensions = _mediaSettings.CartThumbPictureSize; to.DeliveryTimesPresentation = _shoppingCartSettings.DeliveryTimesInShoppingCart; to.DisplayBasePrice = _shoppingCartSettings.ShowBasePrice; to.DisplayWeight = _shoppingCartSettings.ShowWeight; to.DisplayMoveToWishlistButton = await _services.Permissions.AuthorizeAsync(Permissions.Cart.AccessWishlist); to.TermsOfServiceEnabled = _orderSettings.TermsOfServiceEnabled; to.DisplayCommentBox = _shoppingCartSettings.ShowCommentBox; to.DisplayEsdRevocationWaiverBox = _shoppingCartSettings.ShowEsdRevocationWaiverBox; to.IsEditable = isEditable; var measure = await _db.MeasureWeights.FindByIdAsync(_measureSettings.BaseWeightId, false); if (measure != null) { to.MeasureUnitName = measure.GetLocalized(x => x.Name); } to.CheckoutAttributeInfo = HtmlUtils.ConvertPlainTextToTable( HtmlUtils.ConvertHtmlToPlainText( await _checkoutAttributeFormatter.FormatAttributesAsync(customer.GenericAttributes.CheckoutAttributes, customer))); // Gift card and gift card boxes. to.DiscountBox.Display = _shoppingCartSettings.ShowDiscountBox; var discountCouponCode = customer.GenericAttributes.DiscountCouponCode; var discount = await _db.Discounts .AsNoTracking() .Where(x => x.CouponCode == discountCouponCode) .FirstOrDefaultAsync(); if (discount != null && discount.RequiresCouponCode && await _discountService.IsDiscountValidAsync(discount, customer)) { to.DiscountBox.CurrentCode = discount.CouponCode; } to.GiftCardBox.Display = _shoppingCartSettings.ShowGiftCardBox; // Reward points. if (_rewardPointsSettings.Enabled && !from.IncludesMatchingItems(x => x.IsRecurring) && !customer.IsGuest()) { var rewardPointsBalance = customer.GetRewardPointsBalance(); var rewardPointsAmountBase = _orderCalculationService.ConvertRewardPointsToAmount(rewardPointsBalance); var rewardPointsAmount = _currencyService.ConvertFromPrimaryCurrency(rewardPointsAmountBase.Amount, currency); if (rewardPointsAmount > decimal.Zero) { to.RewardPoints.DisplayRewardPoints = true; to.RewardPoints.RewardPointsAmount = rewardPointsAmount.ToString(true); to.RewardPoints.RewardPointsBalance = rewardPointsBalance; to.RewardPoints.UseRewardPoints = customer.GenericAttributes.UseRewardPointsDuringCheckout; } } // Cart warnings. var warnings = new List <string>(); var cartIsValid = await _shoppingCartValidator.ValidateCartItemsAsync(from, warnings, validateCheckoutAttributes, customer.GenericAttributes.CheckoutAttributes); if (!cartIsValid) { to.Warnings.AddRange(warnings); } #endregion #region Checkout attributes var checkoutAttributes = await _checkoutAttributeMaterializer.GetValidCheckoutAttributesAsync(from); foreach (var attribute in checkoutAttributes) { var caModel = new ShoppingCartModel.CheckoutAttributeModel { Id = attribute.Id, Name = attribute.GetLocalized(x => x.Name), TextPrompt = attribute.GetLocalized(x => x.TextPrompt), IsRequired = attribute.IsRequired, AttributeControlType = attribute.AttributeControlType }; if (attribute.IsListTypeAttribute) { var taxFormat = _currencyService.GetTaxFormat(null, null, PricingTarget.Product); var caValues = await _db.CheckoutAttributeValues .AsNoTracking() .Where(x => x.CheckoutAttributeId == attribute.Id) .ToListAsync(); // Prepare each attribute with image and price foreach (var caValue in caValues) { var pvaValueModel = new ShoppingCartModel.CheckoutAttributeValueModel { Id = caValue.Id, Name = caValue.GetLocalized(x => x.Name), IsPreSelected = caValue.IsPreSelected, Color = caValue.Color }; if (caValue.MediaFileId.HasValue && caValue.MediaFile != null) { pvaValueModel.ImageUrl = _mediaService.GetUrl(caValue.MediaFile, _mediaSettings.VariantValueThumbPictureSize, null, false); } caModel.Values.Add(pvaValueModel); // Display price if allowed. if (await _services.Permissions.AuthorizeAsync(Permissions.Catalog.DisplayPrice)) { var priceAdjustmentBase = await _taxCalculator.CalculateCheckoutAttributeTaxAsync(caValue); var priceAdjustment = _currencyService.ConvertFromPrimaryCurrency(priceAdjustmentBase.Price, currency); if (priceAdjustment > 0) { pvaValueModel.PriceAdjustment = "+" + priceAdjustment.WithPostFormat(taxFormat).ToString(); } else if (priceAdjustment < 0) { pvaValueModel.PriceAdjustment = "-" + (priceAdjustment * -1).WithPostFormat(taxFormat).ToString(); } } } } // Set already selected attributes. var selectedCheckoutAttributes = customer.GenericAttributes.CheckoutAttributes; switch (attribute.AttributeControlType) { case AttributeControlType.DropdownList: case AttributeControlType.RadioList: case AttributeControlType.Boxes: case AttributeControlType.Checkboxes: if (selectedCheckoutAttributes.AttributesMap.Any()) { // Clear default selection. foreach (var item in caModel.Values) { item.IsPreSelected = false; } // Select new values. var selectedCaValues = await _checkoutAttributeMaterializer.MaterializeCheckoutAttributeValuesAsync(selectedCheckoutAttributes); foreach (var caValue in selectedCaValues) { foreach (var item in caModel.Values) { if (caValue.Id == item.Id) { item.IsPreSelected = true; } } } } break; case AttributeControlType.TextBox: case AttributeControlType.MultilineTextbox: if (selectedCheckoutAttributes.AttributesMap.Any()) { var enteredText = selectedCheckoutAttributes.GetAttributeValues(attribute.Id)? .Select(x => x.ToString()) .FirstOrDefault(); if (enteredText.HasValue()) { caModel.TextValue = enteredText; } } break; case AttributeControlType.Datepicker: { // Keep in mind my that the code below works only in the current culture. var enteredDate = selectedCheckoutAttributes.AttributesMap .Where(x => x.Key == attribute.Id) .SelectMany(x => x.Value) .FirstOrDefault() .ToString(); if (enteredDate.HasValue() && DateTime.TryParseExact(enteredDate, "D", CultureInfo.CurrentCulture, DateTimeStyles.None, out var selectedDate)) { caModel.SelectedDay = selectedDate.Day; caModel.SelectedMonth = selectedDate.Month; caModel.SelectedYear = selectedDate.Year; } } break; case AttributeControlType.FileUpload: if (selectedCheckoutAttributes.AttributesMap.Any()) { var FileValue = selectedCheckoutAttributes.AttributesMap .Where(x => x.Key == attribute.Id) .Select(x => x.Value.ToString()) .FirstOrDefault(); if (FileValue.HasValue() && caModel.UploadedFileGuid.HasValue() && Guid.TryParse(caModel.UploadedFileGuid, out var guid)) { var download = await _db.Downloads .Include(x => x.MediaFile) .FirstOrDefaultAsync(x => x.DownloadGuid == guid); if (download != null && !download.UseDownloadUrl && download.MediaFile != null) { caModel.UploadedFileName = download.MediaFile.Name; } } } break; default: break; } to.CheckoutAttributes.Add(caModel); } #endregion #region Estimate shipping if (prepareEstimateShippingIfEnabled) { to.EstimateShipping.Enabled = _shippingSettings.EstimateShippingEnabled && from.Any() && from.IncludesMatchingItems(x => x.IsShippingEnabled); if (to.EstimateShipping.Enabled) { // Countries. var defaultEstimateCountryId = setEstimateShippingDefaultAddress && customer.ShippingAddress != null ? customer.ShippingAddress.CountryId : to.EstimateShipping.CountryId; var countriesForShipping = await _db.Countries .AsNoTracking() .ApplyStoreFilter(store.Id) .Where(x => x.AllowsShipping) .ToListAsync(); foreach (var countries in countriesForShipping) { to.EstimateShipping.AvailableCountries.Add(new SelectListItem { Text = countries.GetLocalized(x => x.Name), Value = countries.Id.ToString(), Selected = countries.Id == defaultEstimateCountryId }); } // States. var states = defaultEstimateCountryId.HasValue ? await _db.StateProvinces.AsNoTracking().ApplyCountryFilter(defaultEstimateCountryId.Value).ToListAsync() : new(); if (states.Any()) { var defaultEstimateStateId = setEstimateShippingDefaultAddress && customer.ShippingAddress != null ? customer.ShippingAddress.StateProvinceId : to.EstimateShipping.StateProvinceId; foreach (var s in states) { to.EstimateShipping.AvailableStates.Add(new SelectListItem { Text = s.GetLocalized(x => x.Name), Value = s.Id.ToString(), Selected = s.Id == defaultEstimateStateId }); } } else { to.EstimateShipping.AvailableStates.Add(new SelectListItem { Text = T("Address.OtherNonUS"), Value = "0" }); } if (setEstimateShippingDefaultAddress && customer.ShippingAddress != null) { to.EstimateShipping.ZipPostalCode = customer.ShippingAddress.ZipPostalCode; } } } #endregion #region Cart items var allProducts = from .Select(x => x.Item.Product) .Union(from.Select(x => x.ChildItems).SelectMany(child => child.Select(x => x.Item.Product))) .ToArray(); var batchContext = _productService.CreateProductBatchContext(allProducts, null, customer, false); var subtotal = await _orderCalculationService.GetShoppingCartSubtotalAsync(from.ToList(), null, batchContext); dynamic itemParameters = new ExpandoObject(); itemParameters.TaxFormat = _currencyService.GetTaxFormat(); itemParameters.BatchContext = batchContext; itemParameters.CartSubtotal = subtotal; foreach (var cartItem in from) { var model = new ShoppingCartModel.ShoppingCartItemModel(); await cartItem.MapAsync(model, (object)itemParameters); to.AddItems(model); } #endregion #region Order review data if (prepareAndDisplayOrderReviewData) { var checkoutState = _httpContextAccessor.HttpContext?.GetCheckoutState(); to.OrderReviewData.Display = true; // Billing info. var billingAddress = customer.BillingAddress; if (billingAddress != null) { await MapperFactory.MapAsync(billingAddress, to.OrderReviewData.BillingAddress); } // Shipping info. if (from.IsShippingRequired()) { to.OrderReviewData.IsShippable = true; var shippingAddress = customer.ShippingAddress; if (shippingAddress != null) { await MapperFactory.MapAsync(shippingAddress, to.OrderReviewData.ShippingAddress); } // Selected shipping method. var shippingOption = customer.GenericAttributes.SelectedShippingOption; if (shippingOption != null) { to.OrderReviewData.ShippingMethod = shippingOption.Name; } if (checkoutState != null && checkoutState.CustomProperties.ContainsKey("HasOnlyOneActiveShippingMethod")) { to.OrderReviewData.DisplayShippingMethodChangeOption = !(bool)checkoutState.CustomProperties.Get("HasOnlyOneActiveShippingMethod"); } } if (checkoutState != null && checkoutState.CustomProperties.ContainsKey("HasOnlyOneActivePaymentMethod")) { to.OrderReviewData.DisplayPaymentMethodChangeOption = !(bool)checkoutState.CustomProperties.Get("HasOnlyOneActivePaymentMethod"); } var selectedPaymentMethodSystemName = customer.GenericAttributes.SelectedPaymentMethod; var paymentMethod = await _paymentService.LoadPaymentMethodBySystemNameAsync(selectedPaymentMethodSystemName); // TODO: (ms) (core) Wait for PluginMediator.GetLocalizedFriendlyName implementation //model.OrderReviewData.PaymentMethod = paymentMethod != null ? _pluginMediator.GetLocalizedFriendlyName(paymentMethod.Metadata) : ""; to.OrderReviewData.PaymentSummary = checkoutState.PaymentSummary; to.OrderReviewData.IsPaymentSelectionSkipped = checkoutState.IsPaymentSelectionSkipped; } #endregion var paymentTypes = new PaymentMethodType[] { PaymentMethodType.Button, PaymentMethodType.StandardAndButton }; var boundPaymentMethods = await _paymentService.LoadActivePaymentMethodsAsync( customer, from.ToList(), store.Id, paymentTypes, false); var bpmModel = new ButtonPaymentMethodModel(); foreach (var boundPaymentMethod in boundPaymentMethods) { if (from.IncludesMatchingItems(x => x.IsRecurring) && boundPaymentMethod.Value.RecurringPaymentType == RecurringPaymentType.NotSupported) { continue; } var widgetInvoker = boundPaymentMethod.Value.GetPaymentInfoWidget(); bpmModel.Items.Add(widgetInvoker); } to.ButtonPaymentMethods = bpmModel; }
public PaymentMethod(PaymentMethodType type, User user, CreditCard creditCard) { this.Type = type; this.User = user; this.CreditCard = creditCard; }
public PaymentMethod(PaymentMethodType type, User user, CreditCard creditCard) : this(type, user) { CreditCard = creditCard; }
public virtual IDeviceResponse StartCard(PaymentMethodType paymentMethodType) { throw new UnsupportedTransactionException("This function is not supported by the currently configured device."); }
public async Task SignUpPremiumAsync(User user, string paymentToken, PaymentMethodType paymentMethodType, short additionalStorageGb, UserLicense license) { if (user.Premium) { throw new BadRequestException("Already a premium user."); } if (additionalStorageGb < 0) { throw new BadRequestException("You can't subtract storage!"); } IPaymentService paymentService = null; if (_globalSettings.SelfHosted) { if (license == null || !_licenseService.VerifyLicense(license)) { throw new BadRequestException("Invalid license."); } if (!license.CanUse(user)) { throw new BadRequestException("This license is not valid for this user."); } var dir = $"{_globalSettings.LicenseDirectory}/user"; Directory.CreateDirectory(dir); File.WriteAllText($"{dir}/{user.Id}.json", JsonConvert.SerializeObject(license, Formatting.Indented)); } else { await _paymentService.PurchasePremiumAsync(user, paymentMethodType, paymentToken, additionalStorageGb); } user.Premium = true; user.RevisionDate = DateTime.UtcNow; if (_globalSettings.SelfHosted) { user.MaxStorageGb = 10240; // 10 TB user.LicenseKey = license.LicenseKey; user.PremiumExpirationDate = license.Expires; } else { user.MaxStorageGb = (short)(1 + additionalStorageGb); user.LicenseKey = CoreHelpers.SecureRandomString(20); } try { await SaveUserAsync(user); await _pushService.PushSyncVaultAsync(user.Id); } catch when(!_globalSettings.SelfHosted) { await paymentService.CancelAndRecoverChargesAsync(user); throw; } }
/// <summary> /// This is the default constructor. /// </summary> /// <param name="FareID"></param> /// <param name="Price"></param> /// <param name="CurrencyType"></param> /// <param name="PaymentMethod"></param> /// <param name="Transfers"></param> /// <param name="TransferDuration"></param> public FareAttribute( string FareID, decimal Price, string CurrencyType, PaymentMethodType PaymentMethod, TransferType Transfers, int? TransferDuration ) { mFareID= FareID; mPrice= Price; mCurrencyType= CurrencyType; mPaymentMethod= PaymentMethod; mTransfers= Transfers; mTransferDuration= TransferDuration; }
/// <summary> /// Initializes a new instance of the <see cref="Payment"/> class. /// </summary> /// <param name="paymentMethodType"> /// The payment method type. /// </param> /// <param name="amount"> /// The amount. /// </param> /// <param name="paymentMethodKey"> /// The payment method key. /// </param> internal Payment(PaymentMethodType paymentMethodType, decimal amount, Guid? paymentMethodKey) : this(paymentMethodType, amount, paymentMethodKey, new ExtendedDataCollection()) { }
public async Task <bool> UpdatePaymentMethodAsync(ISubscriber subscriber, PaymentMethodType paymentMethodType, string paymentToken) { if (subscriber == null) { throw new ArgumentNullException(nameof(subscriber)); } if (subscriber.Gateway.HasValue && subscriber.Gateway.Value != GatewayType.Stripe) { throw new GatewayException("Switching from one payment type to another is not supported. " + "Contact us for assistance."); } var createdCustomer = false; Braintree.Customer braintreeCustomer = null; string stipeCustomerSourceToken = null; var stripeCustomerMetadata = new Dictionary <string, string>(); var stripePaymentMethod = paymentMethodType == PaymentMethodType.Card || paymentMethodType == PaymentMethodType.BankAccount; var cardService = new CardService(); var bankSerice = new BankAccountService(); var customerService = new CustomerService(); Customer customer = null; if (!string.IsNullOrWhiteSpace(subscriber.GatewayCustomerId)) { customer = await customerService.GetAsync(subscriber.GatewayCustomerId); if (customer.Metadata?.Any() ?? false) { stripeCustomerMetadata = customer.Metadata; } } var hadBtCustomer = stripeCustomerMetadata.ContainsKey("btCustomerId"); if (stripePaymentMethod) { stipeCustomerSourceToken = paymentToken; } else if (paymentMethodType == PaymentMethodType.PayPal) { if (hadBtCustomer) { var pmResult = await _btGateway.PaymentMethod.CreateAsync(new Braintree.PaymentMethodRequest { CustomerId = stripeCustomerMetadata["btCustomerId"], PaymentMethodNonce = paymentToken }); if (pmResult.IsSuccess()) { var customerResult = await _btGateway.Customer.UpdateAsync( stripeCustomerMetadata["btCustomerId"], new Braintree.CustomerRequest { DefaultPaymentMethodToken = pmResult.Target.Token }); if (customerResult.IsSuccess() && customerResult.Target.PaymentMethods.Length > 0) { braintreeCustomer = customerResult.Target; } else { await _btGateway.PaymentMethod.DeleteAsync(pmResult.Target.Token); hadBtCustomer = false; } } else { hadBtCustomer = false; } } if (!hadBtCustomer) { var customerResult = await _btGateway.Customer.CreateAsync(new Braintree.CustomerRequest { PaymentMethodNonce = paymentToken, Email = subscriber.BillingEmailAddress(), Id = subscriber.BraintreeCustomerIdPrefix() + subscriber.Id.ToString("N").ToLower() + Utilities.CoreHelpers.RandomString(3, upper: false, numeric: false), CustomFields = new Dictionary <string, string> { [subscriber.BraintreeIdField()] = subscriber.Id.ToString() } }); if (!customerResult.IsSuccess() || customerResult.Target.PaymentMethods.Length == 0) { throw new GatewayException("Failed to create PayPal customer record."); } braintreeCustomer = customerResult.Target; } } else { throw new GatewayException("Payment method is not supported at this time."); } if (stripeCustomerMetadata.ContainsKey("btCustomerId")) { if (braintreeCustomer?.Id != stripeCustomerMetadata["btCustomerId"]) { var nowSec = Utilities.CoreHelpers.ToEpocSeconds(DateTime.UtcNow); stripeCustomerMetadata.Add($"btCustomerId_{nowSec}", stripeCustomerMetadata["btCustomerId"]); } stripeCustomerMetadata["btCustomerId"] = braintreeCustomer?.Id; } else if (!string.IsNullOrWhiteSpace(braintreeCustomer?.Id)) { stripeCustomerMetadata.Add("btCustomerId", braintreeCustomer.Id); } try { if (customer == null) { customer = await customerService.CreateAsync(new CustomerCreateOptions { Description = subscriber.BillingName(), Email = subscriber.BillingEmailAddress(), SourceToken = stipeCustomerSourceToken, Metadata = stripeCustomerMetadata }); subscriber.Gateway = GatewayType.Stripe; subscriber.GatewayCustomerId = customer.Id; createdCustomer = true; } if (!createdCustomer) { string defaultSourceId = null; if (stripePaymentMethod) { if (paymentToken.StartsWith("btok_")) { var bankAccount = await bankSerice.CreateAsync(customer.Id, new BankAccountCreateOptions { SourceToken = paymentToken }); defaultSourceId = bankAccount.Id; } else { var card = await cardService.CreateAsync(customer.Id, new CardCreateOptions { SourceToken = paymentToken, }); defaultSourceId = card.Id; } } foreach (var source in customer.Sources.Where(s => s.Id != defaultSourceId)) { if (source is BankAccount) { await bankSerice.DeleteAsync(customer.Id, source.Id); } else if (source is Card) { await cardService.DeleteAsync(customer.Id, source.Id); } } customer = await customerService.UpdateAsync(customer.Id, new CustomerUpdateOptions { Metadata = stripeCustomerMetadata, DefaultSource = defaultSourceId }); } } catch (Exception e) { if (braintreeCustomer != null && !hadBtCustomer) { await _btGateway.Customer.DeleteAsync(braintreeCustomer.Id); } throw e; } return(createdCustomer); }
/// <summary> /// Initializes a new instance of the <see cref="Payment"/> class. /// </summary> /// <param name="paymentMethodType"> /// The payment method type. /// </param> /// <param name="amount"> /// The amount. /// </param> /// <param name="paymentMethodKey"> /// The payment method key. /// </param> /// <param name="extendedData"> /// The extended data. /// </param> internal Payment(PaymentMethodType paymentMethodType, decimal amount, Guid? paymentMethodKey, ExtendedDataCollection extendedData) : this(EnumTypeFieldConverter.PaymentMethod.GetTypeField(paymentMethodType).TypeKey, amount, paymentMethodKey, extendedData) { }
/// <summary> /// Creates and saves a payment /// </summary> /// <param name="paymentMethodType">The type of the paymentmethod</param> /// <param name="amount">The amount of the payment</param> /// <param name="paymentMethodKey">The optional paymentMethodKey</param> /// <returns>Returns <see cref="IPayment"/></returns> public IPayment CreatePaymentWithKey(PaymentMethodType paymentMethodType, decimal amount, Guid?paymentMethodKey) { return(_paymentService.CreatePaymentWithKey(paymentMethodType, amount, paymentMethodKey)); }
/// <summary> /// Initializes a new instance of the <see cref="Payment"/> class. /// </summary> /// <param name="paymentMethodType"> /// The payment method type. /// </param> /// <param name="amount"> /// The amount. /// </param> internal Payment(PaymentMethodType paymentMethodType, decimal amount) : this(paymentMethodType, amount, null, new ExtendedDataCollection()) { }
/// <summary> /// Creates a payment without saving it to the database /// </summary> /// <param name="paymentMethodType">The type of the payment method</param> /// <param name="amount">The amount of the payment</param> /// <param name="paymentMethodKey">The optional payment method Key</param> /// <param name="raiseEvents">Optional boolean indicating whether or not to raise events</param> /// <returns>Returns <see cref="IPayment"/></returns> public IPayment CreatePayment(PaymentMethodType paymentMethodType, decimal amount, Guid? paymentMethodKey, bool raiseEvents = true) { var payment = new Payment(paymentMethodType, amount, paymentMethodKey); if(raiseEvents) if (Creating.IsRaisedEventCancelled(new Events.NewEventArgs<IPayment>(payment), this)) { payment.WasCancelled = true; return payment; } if (raiseEvents) Created.RaiseEvent(new Events.NewEventArgs<IPayment>(payment), this); return payment; }
/// <summary> /// Initializes a new instance of the <see cref="ApmPaymentMethodAllOf" /> class. /// </summary> /// <param name="type">type (required).</param> /// <param name="steps">All steps (already) performed on the payment.</param> public ApmPaymentMethodAllOf(PaymentMethodType type = default(PaymentMethodType), List <PaymentStepResponse> steps = default(List <PaymentStepResponse>)) { this.Type = type; this.Steps = steps; }
public async Task <Tuple <bool, string> > SignUpPremiumAsync(User user, string paymentToken, PaymentMethodType paymentMethodType, short additionalStorageGb, UserLicense license, TaxInfo taxInfo) { if (user.Premium) { throw new BadRequestException("Already a premium user."); } if (additionalStorageGb < 0) { throw new BadRequestException("You can't subtract storage!"); } if ((paymentMethodType == PaymentMethodType.GoogleInApp || paymentMethodType == PaymentMethodType.AppleInApp) && additionalStorageGb > 0) { throw new BadRequestException("You cannot add storage with this payment method."); } string paymentIntentClientSecret = null; IPaymentService paymentService = null; if (_globalSettings.SelfHosted) { if (license == null || !_licenseService.VerifyLicense(license)) { throw new BadRequestException("Invalid license."); } if (!license.CanUse(user)) { throw new BadRequestException("This license is not valid for this user."); } var dir = $"{_globalSettings.LicenseDirectory}/user"; Directory.CreateDirectory(dir); File.WriteAllText($"{dir}/{user.Id}.json", JsonConvert.SerializeObject(license, Formatting.Indented)); } else { paymentIntentClientSecret = await _paymentService.PurchasePremiumAsync(user, paymentMethodType, paymentToken, additionalStorageGb, taxInfo); } user.Premium = true; user.RevisionDate = DateTime.UtcNow; if (_globalSettings.SelfHosted) { user.MaxStorageGb = 10240; // 10 TB user.LicenseKey = license.LicenseKey; user.PremiumExpirationDate = license.Expires; } else { user.MaxStorageGb = (short)(1 + additionalStorageGb); user.LicenseKey = CoreHelpers.SecureRandomString(20); } try { await SaveUserAsync(user); await _pushService.PushSyncVaultAsync(user.Id); await _referenceEventService.RaiseEventAsync( new ReferenceEvent(ReferenceEventType.UpgradePlan, user) { Storage = user.MaxStorageGb, PlanName = PremiumPlanId, }); } catch when(!_globalSettings.SelfHosted) { await paymentService.CancelAndRecoverChargesAsync(user); throw; } return(new Tuple <bool, string>(string.IsNullOrWhiteSpace(paymentIntentClientSecret), paymentIntentClientSecret)); }
/// <summary> /// Load active payment methods /// </summary> /// <param name="customer">Filter payment methods by customer and apply payment method restrictions; null to load all records</param> /// <param name="cart">Filter payment methods by cart amount; null to load all records</param> /// <param name="storeId">Filter payment methods by store identifier; pass 0 to load all records</param> /// <param name="types">Filter payment methods by payment method types</param> /// <param name="provideFallbackMethod">Provide a fallback payment method if none is active</param> /// <returns>Payment methods</returns> public virtual IEnumerable<Provider<IPaymentMethod>> LoadActivePaymentMethods( Customer customer = null, IList<OrganizedShoppingCartItem> cart = null, int storeId = 0, PaymentMethodType[] types = null, bool provideFallbackMethod = true) { List<int> customerRoleIds = null; int? selectedShippingMethodId = null; decimal? orderSubTotal = null; decimal? orderTotal = null; IList<PaymentMethod> allMethods = null; IEnumerable<Provider<IPaymentMethod>> allProviders = null; if (types != null && types.Any()) allProviders = LoadAllPaymentMethods(storeId).Where(x => types.Contains(x.Value.PaymentMethodType)); else allProviders = LoadAllPaymentMethods(storeId); var activeProviders = allProviders .Where(p => { if (!p.Value.IsActive || !_paymentSettings.ActivePaymentMethodSystemNames.Contains(p.Metadata.SystemName, StringComparer.InvariantCultureIgnoreCase)) return false; if (customer != null) { if (allMethods == null) allMethods = GetAllPaymentMethods(); var method = allMethods.FirstOrDefault(x => x.PaymentMethodSystemName.IsCaseInsensitiveEqual(p.Metadata.SystemName)); if (method != null) { // method restricted by customer role id? var excludedRoleIds = method.ExcludedCustomerRoleIds.ToIntArray(); if (excludedRoleIds.Any()) { if (customerRoleIds == null) customerRoleIds = customer.CustomerRoles.Where(r => r.Active).Select(r => r.Id).ToList(); if (customerRoleIds != null && !customerRoleIds.Except(excludedRoleIds).Any()) return false; } // method restricted by selected shipping method? var excludedShippingMethodIds = method.ExcludedShippingMethodIds.ToIntArray(); if (excludedShippingMethodIds.Any()) { if (!selectedShippingMethodId.HasValue) { var selectedShipping = customer.GetAttribute<ShippingOption>(SystemCustomerAttributeNames.SelectedShippingOption, storeId); selectedShippingMethodId = (selectedShipping == null ? 0 : selectedShipping.ShippingMethodId); } if ((selectedShippingMethodId ?? 0) != 0 && excludedShippingMethodIds.Contains(selectedShippingMethodId.Value)) return false; } // method restricted by country of selected billing or shipping address? var excludedCountryIds = method.ExcludedCountryIds.ToIntArray(); if (excludedCountryIds.Any()) { int countryId = 0; if (method.CountryExclusionContext == CountryRestrictionContextType.ShippingAddress) countryId = (customer.ShippingAddress != null ? (customer.ShippingAddress.CountryId ?? 0) : 0); else countryId = (customer.BillingAddress != null ? (customer.BillingAddress.CountryId ?? 0) : 0); if (countryId != 0 && excludedCountryIds.Contains(countryId)) return false; } // method restricted by min\max order amount? if ((method.MinimumOrderAmount.HasValue || method.MaximumOrderAmount.HasValue) && cart != null) { decimal compareAmount = decimal.Zero; if (method.AmountRestrictionContext == AmountRestrictionContextType.SubtotalAmount) { if (!orderSubTotal.HasValue) { decimal orderSubTotalDiscountAmountBase = decimal.Zero; Discount orderSubTotalAppliedDiscount = null; decimal subTotalWithoutDiscountBase = decimal.Zero; decimal subTotalWithDiscountBase = decimal.Zero; _orderTotalCalculationService.GetShoppingCartSubTotal(cart, out orderSubTotalDiscountAmountBase, out orderSubTotalAppliedDiscount, out subTotalWithoutDiscountBase, out subTotalWithDiscountBase); orderSubTotal = _currencyService.ConvertFromPrimaryStoreCurrency(subTotalWithoutDiscountBase, _services.WorkContext.WorkingCurrency); } compareAmount = orderSubTotal.Value; } else if (method.AmountRestrictionContext == AmountRestrictionContextType.TotalAmount) { if (!orderTotal.HasValue) { orderTotal = _orderTotalCalculationService.GetShoppingCartTotal(cart) ?? decimal.Zero; orderTotal = _currencyService.ConvertFromPrimaryStoreCurrency(orderTotal.Value, _services.WorkContext.WorkingCurrency); } compareAmount = orderTotal.Value; } if (method.MinimumOrderAmount.HasValue && compareAmount < method.MinimumOrderAmount.Value) return false; if (method.MaximumOrderAmount.HasValue && compareAmount > method.MaximumOrderAmount.Value) return false; } } } return true; }); if (!activeProviders.Any() && provideFallbackMethod) { var fallbackMethod = allProviders.FirstOrDefault(x => x.IsPaymentMethodActive(_paymentSettings)); if (fallbackMethod == null) fallbackMethod = allProviders.FirstOrDefault(); if (fallbackMethod != null) { return new Provider<IPaymentMethod>[] { fallbackMethod }; } else { if (DataSettings.DatabaseIsInstalled()) throw Error.Application("At least one payment method provider is required to be active."); } } return activeProviders; }
internal Payment(PaymentMethodType paymentMethodType, decimal amount, Guid?paymentMethodKey) : this(paymentMethodType, amount, paymentMethodKey, new ExtendedDataCollection()) { }
protected CheckoutPaymentMethodModel PreparePaymentMethodModel(IList<OrganizedShoppingCartItem> cart) { var model = new CheckoutPaymentMethodModel(); //reward points if (_rewardPointsSettings.Enabled && !cart.IsRecurring()) { int rewardPointsBalance = _workContext.CurrentCustomer.GetRewardPointsBalance(); decimal rewardPointsAmountBase = _orderTotalCalculationService.ConvertRewardPointsToAmount(rewardPointsBalance); decimal rewardPointsAmount = _currencyService.ConvertFromPrimaryStoreCurrency(rewardPointsAmountBase, _workContext.WorkingCurrency); if (rewardPointsAmount > decimal.Zero) { model.DisplayRewardPoints = true; model.RewardPointsAmount = _priceFormatter.FormatPrice(rewardPointsAmount, true, false); model.RewardPointsBalance = rewardPointsBalance; } } var paymentTypes = new PaymentMethodType[] { PaymentMethodType.Standard, PaymentMethodType.Redirection, PaymentMethodType.StandardAndRedirection }; var boundPaymentMethods = _paymentService .LoadActivePaymentMethods(_workContext.CurrentCustomer, cart, _storeContext.CurrentStore.Id, paymentTypes) .ToList(); var allPaymentMethods = _paymentService.GetAllPaymentMethods(); foreach (var pm in boundPaymentMethods) { if (cart.IsRecurring() && pm.Value.RecurringPaymentType == RecurringPaymentType.NotSupported) continue; var paymentMethod = allPaymentMethods.FirstOrDefault(x => x.PaymentMethodSystemName.IsCaseInsensitiveEqual(pm.Metadata.SystemName)); var pmModel = new CheckoutPaymentMethodModel.PaymentMethodModel { Name = _pluginMediator.GetLocalizedFriendlyName(pm.Metadata), Description = _pluginMediator.GetLocalizedDescription(pm.Metadata), PaymentMethodSystemName = pm.Metadata.SystemName, PaymentInfoRoute = pm.Value.GetPaymentInfoRoute(), RequiresInteraction = pm.Value.RequiresInteraction }; if (paymentMethod != null) { pmModel.FullDescription = paymentMethod.GetLocalized(x => x.FullDescription, _workContext.WorkingLanguage.Id); } pmModel.BrandUrl = _pluginMediator.GetBrandImageUrl(pm.Metadata); // payment method additional fee decimal paymentMethodAdditionalFee = _paymentService.GetAdditionalHandlingFee(cart, pm.Metadata.SystemName); decimal rateBase = _taxService.GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, _workContext.CurrentCustomer); decimal rate = _currencyService.ConvertFromPrimaryStoreCurrency(rateBase, _workContext.WorkingCurrency); if (rate != decimal.Zero) pmModel.Fee = _priceFormatter.FormatPaymentMethodAdditionalFee(rate, true); model.PaymentMethods.Add(pmModel); } // find a selected (previously) payment method var selectedPaymentMethodSystemName = _workContext.CurrentCustomer.GetAttribute<string>( SystemCustomerAttributeNames.SelectedPaymentMethod, _genericAttributeService, _storeContext.CurrentStore.Id); bool selected = false; if (selectedPaymentMethodSystemName.HasValue()) { var paymentMethodToSelect = model.PaymentMethods.Find(pm => pm.PaymentMethodSystemName.IsCaseInsensitiveEqual(selectedPaymentMethodSystemName)); if (paymentMethodToSelect != null) { paymentMethodToSelect.Selected = true; selected = true; } } // if no option has been selected, let's do it for the first one if (!selected) { var paymentMethodToSelect = model.PaymentMethods.FirstOrDefault(); if (paymentMethodToSelect != null) paymentMethodToSelect.Selected = true; } return model; }
private PaymentMethod(string value, PaymentMethodType paymentMethodType) { Value = value; PaymentMethodType = paymentMethodType; }
public PaymentMethod(PaymentMethodType type, User user, BankAccount bankAccount) { this.Type = type; this.User = user; this.BankAccount = bankAccount; }
private void PrepareButtonPaymentMethodModel(ButtonPaymentMethodModel model, IList<OrganizedShoppingCartItem> cart) { model.Items.Clear(); var paymentTypes = new PaymentMethodType[] { PaymentMethodType.Button, PaymentMethodType.StandardAndButton }; var boundPaymentMethods = _paymentService .LoadActivePaymentMethods(_workContext.CurrentCustomer, cart, _storeContext.CurrentStore.Id, paymentTypes, false) .ToList(); foreach (var pm in boundPaymentMethods) { if (cart.IsRecurring() && pm.Value.RecurringPaymentType == RecurringPaymentType.NotSupported) continue; string actionName; string controllerName; RouteValueDictionary routeValues; pm.Value.GetPaymentInfoRoute(out actionName, out controllerName, out routeValues); model.Items.Add(new ButtonPaymentMethodModel.ButtonPaymentMethodItem { ActionName = actionName, ControllerName = controllerName, RouteValues = routeValues }); } }
public T WithPaymentMethodType(PaymentMethodType value) { PaymentMethodType = value; return(this as T); }
public BillingTransaction(XmlElement node) : base(node) { foreach (XmlElement propertyNode in node.ChildNodes) { switch (propertyNode.Name) { case "recieptCode": this._RecieptCode = propertyNode.InnerText; continue; case "purchasedItemName": this._PurchasedItemName = propertyNode.InnerText; continue; case "purchasedItemCode": this._PurchasedItemCode = propertyNode.InnerText; continue; case "itemType": this._ItemType = (BillingItemsType)StringEnum.Parse(typeof(BillingItemsType), propertyNode.InnerText); continue; case "billingAction": this._BillingAction = (BillingAction)StringEnum.Parse(typeof(BillingAction), propertyNode.InnerText); continue; case "price": this._Price = ObjectFactory.Create <Price>(propertyNode); continue; case "actionDate": this._ActionDate = ParseLong(propertyNode.InnerText); continue; case "startDate": this._StartDate = ParseLong(propertyNode.InnerText); continue; case "endDate": this._EndDate = ParseLong(propertyNode.InnerText); continue; case "paymentMethod": this._PaymentMethod = (PaymentMethodType)StringEnum.Parse(typeof(PaymentMethodType), propertyNode.InnerText); continue; case "paymentMethodExtraDetails": this._PaymentMethodExtraDetails = propertyNode.InnerText; continue; case "isRecurring": this._IsRecurring = ParseBool(propertyNode.InnerText); continue; case "billingProviderRef": this._BillingProviderRef = ParseInt(propertyNode.InnerText); continue; case "purchaseId": this._PurchaseId = ParseInt(propertyNode.InnerText); continue; case "remarks": this._Remarks = propertyNode.InnerText; continue; } } }
public IDeviceResponse StartCard(PaymentMethodType paymentMethodType) { return(_controller.SendAdminMessage <SipBaseResponse>(new HpaAdminBuilder(HPA_MSG_ID.STARTCARD).Set("CardGroup", paymentMethodType.ToString()))); }
protected CustomerPaymentProviderBase(IRegisteredGatewayProvider registration, ICustomer customer, PaymentMethodType paymentMethodType, decimal amount) : this(registration, customer, EnumTypeFieldConverter.PaymentMethod().GetTypeField(paymentMethodType).TypeKey, amount) { }
/// <summary> /// Creates and saves a payment /// </summary> /// <param name="paymentMethodType">The type of the payment method</param> /// <param name="amount">The amount of the payment</param> /// <param name="paymentMethodKey">The optional payment Method Key</param> /// <param name="raiseEvents">Optional boolean indicating whether or not to raise events</param> /// <returns>Returns <see cref="IPayment"/></returns> public IPayment CreatePaymentWithKey(PaymentMethodType paymentMethodType, decimal amount, Guid?paymentMethodKey, bool raiseEvents = true) { return(CreatePaymentWithKey(EnumTypeFieldConverter.PaymentMethod.GetTypeField(paymentMethodType).TypeKey, amount, paymentMethodKey)); }
public async Task PurchasePremiumAsync(User user, PaymentMethodType paymentMethodType, string paymentToken, short additionalStorageGb) { var invoiceService = new InvoiceService(); var customerService = new CustomerService(); var createdStripeCustomer = false; string stripeCustomerId = null; Braintree.Transaction braintreeTransaction = null; Braintree.Customer braintreeCustomer = null; var stripePaymentMethod = paymentMethodType == PaymentMethodType.Card || paymentMethodType == PaymentMethodType.BankAccount; if (paymentMethodType == PaymentMethodType.BankAccount) { throw new GatewayException("Bank account payment method is not supported at this time."); } if (user.Gateway == GatewayType.Stripe && !string.IsNullOrWhiteSpace(user.GatewayCustomerId)) { try { await UpdatePaymentMethodAsync(user, paymentMethodType, paymentToken); stripeCustomerId = user.GatewayCustomerId; createdStripeCustomer = false; } catch (Exception) { stripeCustomerId = null; } } if (string.IsNullOrWhiteSpace(stripeCustomerId)) { string stipeCustomerSourceToken = null; var stripeCustomerMetadata = new Dictionary <string, string>(); if (stripePaymentMethod) { stipeCustomerSourceToken = paymentToken; } else if (paymentMethodType == PaymentMethodType.PayPal) { var randomSuffix = Utilities.CoreHelpers.RandomString(3, upper: false, numeric: false); var customerResult = await _btGateway.Customer.CreateAsync(new Braintree.CustomerRequest { PaymentMethodNonce = paymentToken, Email = user.Email, Id = user.BraintreeCustomerIdPrefix() + user.Id.ToString("N").ToLower() + randomSuffix, CustomFields = new Dictionary <string, string> { [user.BraintreeIdField()] = user.Id.ToString() } }); if (!customerResult.IsSuccess() || customerResult.Target.PaymentMethods.Length == 0) { throw new GatewayException("Failed to create PayPal customer record."); } braintreeCustomer = customerResult.Target; stripeCustomerMetadata.Add("btCustomerId", braintreeCustomer.Id); } else { throw new GatewayException("Payment method is not supported at this time."); } var customer = await customerService.CreateAsync(new CustomerCreateOptions { Description = user.Name, Email = user.Email, SourceToken = stipeCustomerSourceToken, Metadata = stripeCustomerMetadata }); stripeCustomerId = customer.Id; createdStripeCustomer = true; } var subCreateOptions = new SubscriptionCreateOptions { CustomerId = stripeCustomerId, Items = new List <SubscriptionItemOption>(), Metadata = new Dictionary <string, string> { [user.GatewayIdField()] = user.Id.ToString() } }; subCreateOptions.Items.Add(new SubscriptionItemOption { PlanId = PremiumPlanId, Quantity = 1, }); if (additionalStorageGb > 0) { subCreateOptions.Items.Add(new SubscriptionItemOption { PlanId = StoragePlanId, Quantity = additionalStorageGb }); } var subInvoiceMetadata = new Dictionary <string, string>(); Subscription subscription = null; try { if (!stripePaymentMethod) { var previewInvoice = await invoiceService.UpcomingAsync(new UpcomingInvoiceOptions { CustomerId = stripeCustomerId, SubscriptionItems = ToInvoiceSubscriptionItemOptions(subCreateOptions.Items) }); await customerService.UpdateAsync(stripeCustomerId, new CustomerUpdateOptions { AccountBalance = -1 * previewInvoice.AmountDue }); if (braintreeCustomer != null) { var btInvoiceAmount = (previewInvoice.AmountDue / 100M); var transactionResult = await _btGateway.Transaction.SaleAsync( new Braintree.TransactionRequest { Amount = btInvoiceAmount, CustomerId = braintreeCustomer.Id, Options = new Braintree.TransactionOptionsRequest { SubmitForSettlement = true, PayPal = new Braintree.TransactionOptionsPayPalRequest { CustomField = $"{user.BraintreeIdField()}:{user.Id}" } }, CustomFields = new Dictionary <string, string> { [user.BraintreeIdField()] = user.Id.ToString() } }); if (!transactionResult.IsSuccess()) { throw new GatewayException("Failed to charge PayPal customer."); } braintreeTransaction = transactionResult.Target; subInvoiceMetadata.Add("btTransactionId", braintreeTransaction.Id); subInvoiceMetadata.Add("btPayPalTransactionId", braintreeTransaction.PayPalDetails.AuthorizationId); } else { throw new GatewayException("No payment was able to be collected."); } } var subscriptionService = new SubscriptionService(); subscription = await subscriptionService.CreateAsync(subCreateOptions); if (!stripePaymentMethod && subInvoiceMetadata.Any()) { var invoices = await invoiceService.ListAsync(new InvoiceListOptions { SubscriptionId = subscription.Id }); var invoice = invoices?.FirstOrDefault(); if (invoice == null) { throw new GatewayException("Invoice not found."); } await invoiceService.UpdateAsync(invoice.Id, new InvoiceUpdateOptions { Metadata = subInvoiceMetadata }); } } catch (Exception e) { if (createdStripeCustomer && !string.IsNullOrWhiteSpace(stripeCustomerId)) { await customerService.DeleteAsync(stripeCustomerId); } if (braintreeTransaction != null) { await _btGateway.Transaction.RefundAsync(braintreeTransaction.Id); } if (braintreeCustomer != null) { await _btGateway.Customer.DeleteAsync(braintreeCustomer.Id); } throw e; } user.Gateway = GatewayType.Stripe; user.GatewayCustomerId = stripeCustomerId; user.GatewaySubscriptionId = subscription.Id; user.Premium = true; user.PremiumExpirationDate = subscription.CurrentPeriodEnd; }
protected CheckoutPaymentMethodModel PreparePaymentMethodModel(IList <OrganizedShoppingCartItem> cart) { var model = new CheckoutPaymentMethodModel(); // was shipping skipped var shippingOptions = _shippingService.GetShippingOptions(cart, _workContext.CurrentCustomer.ShippingAddress, "", _storeContext.CurrentStore.Id).ShippingOptions; if (!cart.RequiresShipping() || (shippingOptions.Count <= 1 && _shippingSettings.SkipShippingIfSingleOption)) { model.SkippedSelectShipping = true; } var paymentTypes = new PaymentMethodType[] { PaymentMethodType.Standard, PaymentMethodType.Redirection, PaymentMethodType.StandardAndRedirection }; var boundPaymentMethods = _paymentService .LoadActivePaymentMethods(_workContext.CurrentCustomer, cart, _storeContext.CurrentStore.Id, paymentTypes) .ToList(); var allPaymentMethods = _paymentService.GetAllPaymentMethods(); foreach (var pm in boundPaymentMethods) { if (cart.IsRecurring() && pm.Value.RecurringPaymentType == RecurringPaymentType.NotSupported) { continue; } var paymentMethod = allPaymentMethods.FirstOrDefault(x => x.PaymentMethodSystemName.IsCaseInsensitiveEqual(pm.Metadata.SystemName)); var pmModel = new CheckoutPaymentMethodModel.PaymentMethodModel { Name = _pluginMediator.GetLocalizedFriendlyName(pm.Metadata), Description = _pluginMediator.GetLocalizedDescription(pm.Metadata), PaymentMethodSystemName = pm.Metadata.SystemName, PaymentInfoRoute = pm.Value.GetPaymentInfoRoute(), RequiresInteraction = pm.Value.RequiresInteraction }; if (paymentMethod != null) { pmModel.FullDescription = paymentMethod.GetLocalized(x => x.FullDescription, _workContext.WorkingLanguage.Id); } pmModel.BrandUrl = _pluginMediator.GetBrandImageUrl(pm.Metadata); // payment method additional fee decimal paymentMethodAdditionalFee = _paymentService.GetAdditionalHandlingFee(cart, pm.Metadata.SystemName); decimal rateBase = _taxService.GetPaymentMethodAdditionalFee(paymentMethodAdditionalFee, _workContext.CurrentCustomer); decimal rate = _currencyService.ConvertFromPrimaryStoreCurrency(rateBase, _workContext.WorkingCurrency); if (rate != decimal.Zero) { pmModel.Fee = _priceFormatter.FormatPaymentMethodAdditionalFee(rate, true); } model.PaymentMethods.Add(pmModel); } // find a selected (previously) payment method var selectedPaymentMethodSystemName = _workContext.CurrentCustomer.GetAttribute <string>( SystemCustomerAttributeNames.SelectedPaymentMethod, _genericAttributeService, _storeContext.CurrentStore.Id); bool selected = false; if (selectedPaymentMethodSystemName.HasValue()) { var paymentMethodToSelect = model.PaymentMethods.Find(pm => pm.PaymentMethodSystemName.IsCaseInsensitiveEqual(selectedPaymentMethodSystemName)); if (paymentMethodToSelect != null) { paymentMethodToSelect.Selected = true; selected = true; } } // if no option has been selected, let's do it for the first one if (!selected) { var paymentMethodToSelect = model.PaymentMethods.FirstOrDefault(); if (paymentMethodToSelect != null) { paymentMethodToSelect.Selected = true; } } return(model); }
public IPaymentProcessorPlugin GetPaymentProcessorPlugin(decimal amount, PaymentMethodType methodType) { //TODO: Implement dynamic payment processor options depending on amount var paymentProcessorSystemName = "mobSocial.Plugins.PayPalDirect"; return GetPluginInstance(paymentProcessorSystemName); }