public void GivenTheFollowingTransaction(string category, string paymentMethod, Table data) { _paymentMethodService = new PaymentMethodService(new PaymentMethodRepository(context)); switch (_transactionType) { case TransactionTypes.Income: _transaction = data.CreateInstance <Income>(); _transactionService = new IncomeService(new IncomeRepository(context)); _categoryService = new IncomeCategoryService(new IncomeCategoryRepository(context)); break; case TransactionTypes.Expense: _transaction = data.CreateInstance <Expense>(); _transactionService = new ExpenseService(new ExpenseRepository(context)); _categoryService = new ExpenseCategoryService(new ExpenseCategoryRepository(context)); break; } _paymentMethod = _paymentMethodService.Create(paymentMethod); _transaction.Method = _paymentMethod; _transaction.PaymentMethodId = _paymentMethod.Id; _category = _categoryService.Create(category); _transaction.Category = _category; _transaction.CategoryId = _category.Id; _transaction.Date = DateTime.Today; _transaction.Id = 1; _transactionService.Create(_transaction); }
public void GivenTheFollowingTransaction(string category, string paymentMethod, Table data) { _paymentMethodService = new PaymentMethodService(new PaymentMethodRepository(context)); switch (_transactionType) { case TransactionTypes.Income: _transaction = data.CreateInstance<Income>(); _transactionService = new IncomeService(new IncomeRepository(context)); _categoryService = new IncomeCategoryService(new IncomeCategoryRepository(context)); break; case TransactionTypes.Expense: _transaction = data.CreateInstance<Expense>(); _transactionService = new ExpenseService(new ExpenseRepository(context)); _categoryService = new ExpenseCategoryService(new ExpenseCategoryRepository(context)); break; } _paymentMethod = _paymentMethodService.Create(paymentMethod); _transaction.Method = _paymentMethod; _transaction.PaymentMethodId = _paymentMethod.Id; _category = _categoryService.Create(category); _transaction.Category = _category; _transaction.CategoryId = _category.Id; _transaction.Date = DateTime.Today; _transaction.Id = 1; _transactionService.Create(_transaction); }
public Subscription Purchase(string email, string cardCvc, string cardNumber, long cardExpirationMonth, long cardExpirationYear) { StripeConfiguration.ApiKey = Configuration.STRIPE_API_SECRET_KEY; var customerSvc = new CustomerService(); var customer = GetOrCreateCustomer(customerSvc, email); var paymentMethodService = new PaymentMethodService(); var paymentMethod = paymentMethodService.Create( new PaymentMethodCreateOptions { Type = "card", Card = new PaymentMethodCardCreateOptions { Cvc = cardCvc, Number = cardNumber, ExpMonth = cardExpirationMonth, ExpYear = cardExpirationYear }, }); paymentMethod = paymentMethodService.Attach( paymentMethod.Id, new PaymentMethodAttachOptions { Customer = customer.Id }); var subscriptionSvc = new SubscriptionService(); var subscription = GetOrCreateSubscription(subscriptionSvc, customer, Configuration.STRIPE_INCOME_CALCULATOR_PRODUCT_PLAN_ID, paymentMethod.Id); return(subscription); }
public SubscriptionResult Create(User user, string email, string paymentToken, string planId) { var paymentMethodCreate = new PaymentMethodCreateOptions { Card = new PaymentMethodCardCreateOptions { Token = paymentToken }, Type = "card" }; var pmService = new PaymentMethodService(); var paymentMethod = pmService.Create(paymentMethodCreate); Console.WriteLine("Payment method: " + paymentMethod.Id); var custOptions = new CustomerCreateOptions { Email = email, PaymentMethod = paymentMethod.Id, InvoiceSettings = new CustomerInvoiceSettingsOptions { DefaultPaymentMethod = paymentMethod.Id, }, Metadata = new Dictionary <string, string> { { "userid", user.Id.ToString() } } }; var custService = new CustomerService(); var customer = custService.Create(custOptions); Console.WriteLine("Customer: " + customer.Id); var items = new List <SubscriptionItemOptions> { new SubscriptionItemOptions { Plan = planId, } }; var subscriptionOptions = new SubscriptionCreateOptions { Customer = customer.Id, Items = items, TrialPeriodDays = 7 }; subscriptionOptions.AddExpand("latest_invoice.payment_intent"); var subService = new SubscriptionService(); var subscription = subService.Create(subscriptionOptions); Console.WriteLine("Subscription: " + subscription.Id); return(new SubscriptionResult( customerId: customer.Id, subscriptionId: subscription.Id)); }
public void Init() { StripeConfiguration.ApiKey = ApiKey; var cRes = new CustomerService().Create(new CustomerCreateOptions() { Email = "*****@*****.**", Name = "Mark Christopher", }); var paymentMethodCreateOptions = new PaymentMethodCreateOptions { Type = "card", Card = new PaymentMethodCardCreateOptions() { Number = "4242424242424242", ExpMonth = 1, ExpYear = 2021, Cvc = "314", }, BillingDetails = new BillingDetailsOptions() { Name = "Mark", Address = new AddressOptions() { PostalCode = "3700", City = "Bayombong" }, Email = "*****@*****.**", Phone = "09067701852" }, }; var paymentMethodService = new PaymentMethodService(); var res = paymentMethodService.Create(paymentMethodCreateOptions); // `source` is obtained with Stripe.js; see https://stripe.com/docs/payments/accept-a-payment-charges#web-create-token var chargeCreateOptions = new ChargeCreateOptions { Amount = 2000, Currency = "usd", Source = "tok_visa", Description = "Charge for [email protected]", }; var chargeService = new ChargeService(); var iRes = chargeService.Create(chargeCreateOptions); }
public ActionResult AddAccount(PaymentMethodViewModel m) { var expMonthInt = Int32.Parse(m.ExpMonth); var expYearInt = Int32.Parse(m.ExpYear); if (ModelState.IsValid) { m.CardType = m.CardNumber.Substring(0, 1); //m.AccountName = m.CardType + " ending in " + m.CardNumber.Substring(m.CardNumber.Length - 4); m.AccountName = " ending in " + m.CardNumber.Substring(m.CardNumber.Length - 4); StripeConfiguration.ApiKey = "sk_test_51H4bEIAVJDEhYcbP8AniC54IhmNxi8AOAkQpTgSCdwJjXwd8eoYEZmpBdZPOn7mpkBhQWkuzYYIFUv1y8Y3ncnKO008t1vsMSK"; var paymentMethodService = new PaymentMethodService(); //need to send the first digit of the card number to the account list and user account table var paymentMethod = paymentMethodService.Create(new PaymentMethodCreateOptions { Type = "card", Card = new PaymentMethodCardCreateOptions { Number = m.CardNumber, Cvc = m.CvcCode, ExpMonth = expMonthInt, ExpYear = expYearInt, } }); ModelState.AddModelError(String.Empty, paymentMethod.Id); var options = new CustomerCreateOptions { Description = m.AccountName }; var services = new CustomerService(); var cust = services.Create(options); // why do we need to create a useraccount object instead of just using paymentmethodviewmodel object? var userAccount = new UserAccount() { AccountName = m.AccountName, BankReference = paymentMethod.Id, CardType = m.CardType, UserID = currentUser.UserId, Customer = cust.Id }; Dc.UserAccounts.Add(userAccount); Dc.SaveChanges(); return(RedirectToAction("AccountList", "Billing", userAccount));//redirects user to different action" } return(View(m)); }
public void WhenIChangeTheTo(Properties propChanging, string value) { // ReSharper disable once SwitchStatementMissingSomeCases switch (propChanging) { case Properties.Date: _transaction.Date = DateTime.Parse(value != "" ? value : DateTime.Now.ToString(CultureInfo.InvariantCulture)); break; case Properties.Amount: _transaction.Amount = decimal.Parse(value); break; case Properties.Comment: _transaction.Comments = value; break; case Properties.Category: if (!string.IsNullOrWhiteSpace(value)) { _transaction.Category = _categoryService.Create(value); _transaction.CategoryId = _transaction.Category.Id; } else { _transaction.CategoryId = 0; } break; case Properties.Method: if (!string.IsNullOrWhiteSpace(value)) { _transaction.Method = _paymentMethodService.Create(value); _transaction.PaymentMethodId = _transaction.Method.Id; } else { _transaction.PaymentMethodId = 0; } break; } try { _transactionService.Save(_transaction); } catch (Exception e) { _scenarioContext.Add(ExceptionContextKey, e); } }
public void WhenIChangeTheTo(Properties propChanging, string value) { switch (propChanging) { case Properties.Date: _transaction.Date = DateTime.Parse(value != "" ? value : DateTime.Now.ToString()); break; case Properties.Amount: _transaction.Amount = decimal.Parse(value); break; case Properties.Comment: _transaction.Comments = value; break; case Properties.Category: if (!string.IsNullOrWhiteSpace(value)) { _transaction.Category = _categoryService.Create(value); _transaction.CategoryId = _transaction.Category.Id; } else { _transaction.CategoryId = 0; } break; case Properties.Method: if (!string.IsNullOrWhiteSpace(value)) { _transaction.Method = _paymentMethodService.Create(value); _transaction.PaymentMethodId = _transaction.Method.Id; } else { _transaction.PaymentMethodId = 0; } break; } try { _transactionService.Save(_transaction); } catch (Exception e) { ScenarioContext.Current.Add(EXCEPTION_CONTEXT_KEY, e); } }
public static PaymentMethod CreateCardPaymentMethod(string cardNumber, long expMonth, long expYear, string cvc, PaymentMethodService paymentMethodService) { // Create a payment method var options = new PaymentMethodCreateOptions { Type = "card", Card = new PaymentMethodCardCreateOptions { Number = cardNumber, ExpMonth = expMonth, ExpYear = expYear, Cvc = cvc, }, }; return(paymentMethodService.Create(options)); }
public async Task <IActionResult> CreateCardPaymentMethod() { PayModel paymodel = getPayModel(); var options = new PaymentMethodCreateOptions { Customer = "Nahed Kadih", Type = "card", Card = new PaymentMethodCardOptions { Number = paymodel.CardNumder, ExpMonth = paymodel.ExpMonth, ExpYear = paymodel.ExpYear, Cvc = paymodel.CVC, }, BillingDetails = new PaymentMethodBillingDetailsOptions { Name = "Nahed Kadih", Address = new Stripe.AddressOptions { PostalCode = paymodel.AddressZip, City = paymodel.AddressCity }, Email = "*****@*****.**", Phone = "09067701852" }, }; var paymentMethodService = new PaymentMethodService(); PaymentMethod paaymentMethoden = paymentMethodService.Create(options); // `source` is obtained with Stripe.js; see https://stripe.com/docs/payments/accept-a-payment-charges#web-create-token //var chargeCreateOptions = new ChargeCreateOptions //{ // Amount = 2000, // Currency = "usd", // Source = "tok_visa", // Description = "Charge for [email protected]", //}; //var chargeService = new ChargeService(); //var iRes = chargeService.Create(chargeCreateOptions); var response = await Task.FromResult(paaymentMethoden); return(Ok(response)); }
public void WhenIPressAdd() { try { if (_category != null) { _category = _categoryService.Create(_category?.Name ?? "not this one"); _transaction.CategoryId = _category.Id; } if (_paymentMethod != null) { _paymentMethod = _paymentMethodService.Create(_paymentMethod?.Name ?? "not this one"); _transaction.PaymentMethodId = _paymentMethod.Id; } _transactionService.Create(_transaction); } catch (Exception e) { ScenarioContext.Current.Add(ExceptionContextKey, e); } }
public ActionResult BasicInfo(PaymentMethodEditorModel model, string @return) { PaymentMethod method = null; if (model.Id > 0) { method = _paymentMethodService.Find(model.Id); model.UpdateTo(method); } else { method = new PaymentMethod(); model.UpdateTo(method); _paymentMethodService.Create(method); } if (model.Id > 0) { CurrentInstance.Database.SaveChanges(); } string redirectUrl = null; var processor = _processorProvider.FindByName(method.ProcessorName); var editor = processor as IHasCustomPaymentProcessorConfigEditor; if (editor != null || processor.ConfigType != null) { redirectUrl = Url.Action("Processor", RouteValues.From(Request.QueryString).Merge("id", method.Id)); } else { redirectUrl = Url.Action("Complete", RouteValues.From(Request.QueryString).Merge("id", method.Id)); } return(AjaxForm().RedirectTo(redirectUrl)); }
public dynamic createPayment(CardInfo cardInfo) { try { int paymentAmount = cardInfo.Amount; if (cardInfo.CardNumber != null) { StripeConfiguration.ApiKey = GetEnvironmentConfigVar(StripeConfigKey, this.configuration.GetValue <string>(StripeConfigKey)); var options = new PaymentMethodCreateOptions { Type = "card", Card = new PaymentMethodCardCreateOptions { Number = cardInfo.CardNumber, ExpMonth = Convert.ToInt32(cardInfo.CardExpiryMonth), ExpYear = Convert.ToInt32(cardInfo.CardExpiryYear), Cvc = cardInfo.CardCVC, }, }; var service = new PaymentMethodService(); var paymentMethod = service.Create(options); PaymentIntent paymentIntentObj = createPaymentIntent(paymentMethod.Id, paymentAmount); return(new { payment_method_id = paymentMethod.Id, payment_intent_id = paymentIntentObj.Id, status = paymentIntentObj.Status }); } else { return(new { customError = "Something is wrong. Pleas fill out all the information" }); } } catch (StripeException e) { return(new { error = e.StripeError.Message }); } return(new { customError = "Payment method not created" }); }
public static void AddNewPaymentOption(string cardNumber, int expiryMonth, int expiryYear, string cvc) { StripeConfiguration.ApiKey = Constants.StripeKey; var options = new PaymentMethodCreateOptions { Type = "card", Card = new PaymentMethodCardCreateOptions { Number = cardNumber, ExpMonth = expiryMonth, ExpYear = expiryYear, Cvc = cvc } }; var service = new PaymentMethodService(); PaymentMethod pmMethod = service.Create(options); var attachOptions = new PaymentMethodAttachOptions { Customer = App.PaymentId }; var attachService = new PaymentMethodService(); attachService.Attach(pmMethod.Id, attachOptions); }
public async Task <IActionResult> Charge([FromBody] PaymentRequest paymentRequest) { try { var customers = new CustomerService(); var Charges = new ChargeService(); var Checkcustomer = await _paymentService.GetCustomerPaymentId(paymentRequest.UserId); var customer = new Customer(); var CustomerId = ""; if (Checkcustomer == null) { customer = customers.Create(new CustomerCreateOptions { Email = paymentRequest.CustomerEmail, Name = paymentRequest.CustomerName, Phone = paymentRequest.CustomerPhone, }); CustomerId = customer.Id; } else { CustomerId = Checkcustomer.CustomerPaymentId; } var options1 = new PaymentMethodCreateOptions { Type = "card", Card = new PaymentMethodCardCreateOptions { Number = paymentRequest.CardNumber, ExpMonth = paymentRequest.ExpMonth, ExpYear = paymentRequest.ExpYear, Cvc = paymentRequest.Cvc }, }; var service1 = new PaymentMethodService(); service1.Create(options1); var options = new PaymentIntentCreateOptions { Amount = paymentRequest.Amount, Currency = "USD", Customer = CustomerId, PaymentMethod = paymentRequest.PaymentMethod, Confirm = true, PaymentMethodTypes = new List <string> { "card" }, }; var service = new PaymentIntentService(); var intent = service.Create(options); if (intent.Status == "succeeded") { var PaymentTrans = new PaymentTransaction { UserId = paymentRequest.UserId, CustomerPaymentId = CustomerId }; await Create(PaymentTrans); return(Ok(new { status = Ok().StatusCode, message = "Payment Successfully" })); } return(BadRequest(new { status = BadRequest().StatusCode, message = "Internal server error" })); } catch (Exception ex) { return(BadRequest(new { status = BadRequest().StatusCode, message = ex.Message })); } }
// Moved to Transaction.cs // private string customerId; // private string paymentMethodId; public override int GetToken(Payment payment) { int ret = 10; err = ""; payToken = ""; customerId = ""; paymentMethodId = ""; strResult = ""; resultCode = "991"; resultMsg = "Fail"; Tools.LogInfo("GetToken/10", "Merchant Ref=" + payment.MerchantReference, 10, this); try { // Testing // StripeConfiguration.ApiKey = "sk_test_51It78gGmZVKtO2iKBZF7DA5JisJzRqvibQdXSfBj9eQh4f5UDvgCShZIjznOWCxu8MtcJG5acVkDcd8K184gIegx001uXlHI5g"; // Testing ret = 20; StripeConfiguration.ApiKey = payment.ProviderPassword; // Secret key ret = 30; var tokenOptions = new TokenCreateOptions { Card = new TokenCardOptions { Number = payment.CardNumber, ExpMonth = payment.CardExpiryMonth, ExpYear = payment.CardExpiryYear, Cvc = payment.CardCVV } }; ret = 40; var tokenService = new TokenService(); var token = tokenService.Create(tokenOptions); payToken = token.Id; err = err + ", tokenId=" + Tools.NullToString(payToken); ret = 50; var paymentMethodOptions = new PaymentMethodCreateOptions { Type = "card", Card = new PaymentMethodCardOptions { Token = token.Id } }; ret = 60; var paymentMethodService = new PaymentMethodService(); var paymentMethod = paymentMethodService.Create(paymentMethodOptions); paymentMethodId = paymentMethod.Id; err = err + ", paymentMethodId=" + Tools.NullToString(paymentMethodId); ret = 70; string tmp = (payment.FirstName + " " + payment.LastName).Trim(); var customerOptions = new CustomerCreateOptions { Name = payment.CardName, // (payment.FirstName + " " + payment.LastName).Trim(), Email = payment.EMail, Phone = payment.PhoneCell, Description = payment.MerchantReference + (tmp.Length > 0 ? " (" + tmp + ")" : ""), PaymentMethod = paymentMethod.Id }; ret = 75; if (payment.Address1(0).Length > 0 || payment.Address2(0).Length > 0 || payment.ProvinceCode.Length > 0 || payment.CountryCode(0).Length > 0) { ret = 80; customerOptions.Address = new AddressOptions() { Line1 = payment.Address1(0), // Line2 = payment.Address2(0), City = payment.Address2(0), State = payment.ProvinceCode, PostalCode = payment.PostalCode(0) }; ret = 85; if (payment.CountryCode(0).Length == 2) { customerOptions.Address.Country = payment.CountryCode(0).ToUpper(); } } ret = 90; var customerService = new CustomerService(); var customer = customerService.Create(customerOptions); // customer.Currency = payment.CurrencyCode.ToLower(); customerId = customer.Id; err = err + ", customerId=" + Tools.NullToString(customerId); ret = 100; strResult = customer.StripeResponse.Content; // resultMsg = Tools.JSONValue(strResult,"status"); resultCode = customer.StripeResponse.ToString(); int k = resultCode.ToUpper().IndexOf(" STATUS="); ret = 110; err = err + ", StripeResponse=" + Tools.NullToString(resultCode); // customer.StripeResponse.ToString() is as follows: // <Stripe.StripeResponse status=200 Request-Id=req_bI0B5glG6r6DNe Date=2021-05-28T09:35:23> if (k > 0) { resultCode = resultCode.Substring(k + 8).Trim(); k = resultCode.IndexOf(" "); if (k > 0) { resultCode = resultCode.Substring(0, k); } } else { resultCode = "999"; } ret = 120; err = err + ", strResult=" + Tools.NullToString(strResult) + ", resultCode=" + Tools.NullToString(resultCode); customer = null; customerService = null; customerOptions = null; paymentMethod = null; paymentMethodService = null; paymentMethodOptions = null; token = null; tokenService = null; tokenOptions = null; if (resultCode.StartsWith("2") && payToken.Length > 0 && paymentMethodId.Length > 0 && customerId.Length > 0) { resultMsg = "Success"; ret = 0; // Tools.LogInfo ("GetToken/189","Ret=0" + err,255,this); } else { Tools.LogInfo("GetToken/197", "Ret=" + ret.ToString() + err, 231, this); } } catch (Exception ex) { err = "Ret=" + ret.ToString() + err; Tools.LogInfo("GetToken/198", err, 231, this); Tools.LogException("GetToken/199", err, ex, this); } return(ret); }
public static async Task <dynamic> CreateClientAsync(string email, string name, string cardNumber, int month, int year, string cvv) { var optionstoken = new TokenCreateOptions { Card = new CreditCardOptions { Number = cardNumber, ExpMonth = month, ExpYear = year, Cvc = cvv } }; var servicetoken = new TokenService(); Token stripetoken = await servicetoken.CreateAsync(optionstoken); var customer = new CustomerCreateOptions { Email = email, Name = name, Source = stripetoken.Id, }; Console.WriteLine(" stripetoken attributes :" + stripetoken); var services = new CustomerService(); var created = services.Create(customer); var option = new PaymentMethodCreateOptions { Type = "card", Card = new PaymentMethodCardCreateOptions { Number = cardNumber, ExpMonth = month, ExpYear = year, Cvc = cvv, }, }; var service = new PaymentMethodService(); var result = service.Create(option); Console.WriteLine(" PaymentMethodService attributes :" + result); var options = new PaymentMethodAttachOptions { Customer = created.Id, }; var method = new PaymentMethodService(); method.Attach( result.Id, options ); if (created.Id == null) { return("Failed"); } else { return(created.Id); } }
public override int ThreeDSecurePayment(Payment payment, Uri postBackURL, string languageCode = "", string languageDialectCode = "") { int ret = 10; string url = ""; err = ""; try { StripeConfiguration.ApiKey = payment.ProviderPassword; // Secret key if (postBackURL == null) { url = Tools.ConfigValue("SystemURL"); } else { url = postBackURL.GetLeftPart(UriPartial.Authority); } if (!url.EndsWith("/")) { url = url + "/"; } d3Form = ""; ret = 20; url = url + "RegisterThreeD.aspx?ProviderCode=" + bureauCode + "&TransRef=" + Tools.XMLSafe(payment.MerchantReference); ret = 50; var paymentMethodOptions = new PaymentMethodCreateOptions { Type = "card", Card = new PaymentMethodCardOptions { Number = payment.CardNumber, ExpMonth = payment.CardExpiryMonth, ExpYear = payment.CardExpiryYear, Cvc = payment.CardCVV } }; ret = 60; var paymentMethodService = new PaymentMethodService(); var paymentMethod = paymentMethodService.Create(paymentMethodOptions); err = err + ", paymentMethodId=" + Tools.NullToString(paymentMethod.Id); ret = 70; var customerOptions = new CustomerCreateOptions { Name = payment.CardName, // (payment.FirstName + " " + payment.LastName).Trim(), Email = payment.EMail, Phone = payment.PhoneCell, PaymentMethod = paymentMethod.Id }; ret = 80; var customerService = new CustomerService(); var customer = customerService.Create(customerOptions); err = err + ", customerId=" + Tools.NullToString(customer.Id); // if ( payment.PaymentDescription.Length < 1 ) // payment.PaymentDescription = "CareAssist"; // else if ( payment.PaymentDescription.Length > 22 ) // payment.PaymentDescription = payment.PaymentDescription.Substring(0,22); // Stripe needs a minimum payment of 50 US cents var paymentIntentOptions = new PaymentIntentCreateOptions { Amount = 050, // payment.PaymentAmount, Currency = "usd", // payment.CurrencyCode.ToLower(), // Must be "usd" not "USD" StatementDescriptor = payment.PaymentDescriptionLeft(22), Customer = customer.Id, PaymentMethod = paymentMethod.Id, Description = payment.MerchantReference, ConfirmationMethod = "manual" }; ret = 40; var paymentIntentService = new PaymentIntentService(); var paymentIntent = paymentIntentService.Create(paymentIntentOptions); err = err + ", paymentIntentId=" + Tools.NullToString(paymentIntent.Id); ret = 50; var confirmOptions = new PaymentIntentConfirmOptions { PaymentMethod = paymentMethod.Id, ReturnUrl = url }; ret = 60; var paymentConfirm = paymentIntentService.Confirm(paymentIntent.Id, confirmOptions); payRef = paymentConfirm.Id; err = err + ", paymentConfirmId=" + Tools.NullToString(payRef); ret = 70; strResult = paymentConfirm.StripeResponse.Content; d3Form = Tools.JSONValue(strResult, "url", "next_action"); d3Form = Tools.JSONRaw(d3Form); resultMsg = Tools.JSONValue(strResult, "status"); ret = 80; resultCode = paymentConfirm.StripeResponse.ToString(); int k = resultCode.ToUpper().IndexOf(" STATUS="); err = err + ", StripeResponse=" + Tools.NullToString(resultCode); ret = 90; Tools.LogInfo("ThreeDSecurePayment/60", "strResult=" + strResult, 221, this); string sql = "exec sp_WP_PaymentRegister3DSecA @ContractCode=" + Tools.DBString(payment.MerchantReference) + ",@ReferenceNumber=" + Tools.DBString(payRef) + ",@Status='77'"; // Means payment pending if (languageCode.Length > 0) { sql = sql + ",@LanguageCode=" + Tools.DBString(languageCode); } if (languageDialectCode.Length > 0) { sql = sql + ",@LanguageDialectCode=" + Tools.DBString(languageDialectCode); } using (MiscList mList = new MiscList()) mList.ExecQuery(sql, 0, "", false, true); Tools.LogInfo("ThreeDSecurePayment/80", "PayRef=" + payRef + "; SQL=" + sql + "; " + d3Form, 10, this); return(0); } catch (Exception ex) { Tools.LogException("ThreeDSecurePayment/99", "Ret=" + ret.ToString(), ex, this); } return(ret); }
public static TransactionResult CreateSubscription(TransactionRequest request, StripeSettings stripeSettings, ILogger logger) { var order = request.Order; InitStripe(stripeSettings); var parameters = request.Parameters; parameters.TryGetValue("cardNumber", out var cardNumber); parameters.TryGetValue("cardName", out var cardName); parameters.TryGetValue("expireMonth", out var expireMonthStr); parameters.TryGetValue("expireYear", out var expireYearStr); parameters.TryGetValue("cvv", out var cvv); var paymentMethodService = new PaymentMethodService(); var paymentMethod = paymentMethodService.Create(new PaymentMethodCreateOptions() { Card = new PaymentMethodCardCreateOptions() { Number = cardNumber.ToString(), ExpYear = long.Parse(expireYearStr.ToString()), ExpMonth = long.Parse(expireMonthStr.ToString()), Cvc = cvv.ToString() }, Type = "card" }); var address = DependencyResolver.Resolve <IDataSerializer>() .DeserializeAs <Address>(order.BillingAddressSerialized); InitStripe(stripeSettings, true); //do we have a saved stripe customer id? var customerId = GetCustomerId(order.User, paymentMethod, address); var subscriptionItems = new List <SubscriptionItemOptions>(); var productService = new ProductService(); var planService = new PlanService(); foreach (var orderItem in order.OrderItems) { var product = productService.Create(new ProductCreateOptions { Name = orderItem.Product.Name, Type = "service" }); var lineTotal = orderItem.Price * orderItem.Quantity + orderItem.Tax; GetFinalAmountDetails(lineTotal, order.CurrencyCode, address, out var currencyCode, out var finalAmount); var planOptions = new PlanCreateOptions() { Nickname = product.Name, Product = product.Id, Amount = (long)(finalAmount), Interval = GetInterval(orderItem.Product.SubscriptionCycle), IntervalCount = orderItem.Product.CycleCount == 0 ? 1 : orderItem.Product.CycleCount, Currency = currencyCode, UsageType = "licensed", TrialPeriodDays = orderItem.Product.TrialDays }; var plan = planService.Create(planOptions); subscriptionItems.Add(new SubscriptionItemOptions() { Plan = plan.Id, Quantity = orderItem.Quantity }); } //create a coupon if any var coupon = GetCoupon(order); var subscriptionOptions = new SubscriptionCreateOptions() { Customer = customerId, Items = subscriptionItems, Metadata = new Dictionary <string, string>() { { "orderGuid", order.Guid }, { "internalId", order.Id.ToString() }, { "isSubscription", bool.TrueString } }, Coupon = coupon?.Id, #if DEBUG TrialEnd = DateTime.UtcNow.AddMinutes(5) #endif }; subscriptionOptions.AddExpand("latest_invoice.payment_intent"); var subscriptionService = new SubscriptionService(); var subscription = subscriptionService.Create(subscriptionOptions); var processPaymentResult = new TransactionResult() { OrderGuid = order.Guid, }; if (subscription.Status == "active" || subscription.Status == "trialing") { processPaymentResult.NewStatus = PaymentStatus.Complete; processPaymentResult.TransactionCurrencyCode = order.CurrencyCode; processPaymentResult.IsSubscription = true; processPaymentResult.TransactionAmount = (subscription.Plan.AmountDecimal / 100) ?? order.OrderTotal; processPaymentResult.ResponseParameters = new Dictionary <string, object>() { { "subscriptionId", subscription.Id }, { "invoiceId", subscription.LatestInvoiceId }, { "feePercent", subscription.ApplicationFeePercent }, { "collectionMethod", subscription.CollectionMethod }, { "metaInfo", subscription.Metadata } }; processPaymentResult.Success = true; } else { processPaymentResult.Success = false; logger.Log <TransactionResult>(LogLevel.Warning, $"The subscription for Order#{order.Id} by stripe failed with status {subscription.Status}." + subscription.StripeResponse.Content); } return(processPaymentResult); }
protected void PlaceOrder_Click(object sender, EventArgs e) { var totalPrice = int.Parse(hdnTotalPrice.Value) * 100; #region Create a Payment Method var paymentMethodCreateOptions = new PaymentMethodCreateOptions { Type = "card", Card = new PaymentMethodCardOptions { Number = cardnumber.Value, ExpMonth = long.Parse(expiryMonth.Value), ExpYear = long.Parse(expiryYear.Value), Cvc = cvvCode.Value, }, }; var paymentMethodService = new PaymentMethodService(); PaymentMethod paymentMethodResult = null; try { paymentMethodResult = paymentMethodService.Create(paymentMethodCreateOptions); } catch (StripeException ex) { switch (ex.StripeError.Type) { case "card_error": // Log Error details to your application Database // ex.StripeError.Code, ex.StripeError.Message, ex.StripeError.DocUrl, ex.StripeError.DeclineCode // Show a friendly message to the end user errorMessage.Text = "We are sorry, but we are unable to charge your credit card. Please ensure that " + "your credit card details are right and you have enough funds in it and try again."; break; case "api_connection_error": errorMessage.Text = "We are sorry but we couldn't charge your card. Please try again."; break; case "validation_error": errorMessage.Text = "We are sorry, but we are unable to charge your credit card. Please ensure that " + "your credit card details are right and you have enough funds in it and try again."; break; case "api_error": // 500 errors, very rare case "authentication_error": case "invalid_request_error": case "rate_limit_error": default: // Unknown Error Type errorMessage.Text = "We are sorry but we couldn't charge your card due to an issue on our end." + "Our engineers have been notified. Please wait for 24 hours and retry again. If the issue " + "isn't resovled still, then please call us on our customer care center at 1 800 123 1234."; break; } errorMessage.Visible = true; return; } #endregion #region Create & Confirm PaymentIntent OR Charge the card var paymentIntentCreateOptions = new PaymentIntentCreateOptions { Amount = totalPrice, Currency = "sgd", PaymentMethodTypes = new List <string> { "card" }, Confirm = true, PaymentMethod = paymentMethodResult.Id }; var paymentIntentService = new PaymentIntentService(); PaymentIntent paymentIntentResult; try { paymentIntentResult = paymentIntentService.Create(paymentIntentCreateOptions); } catch (StripeException ex) { switch (ex.StripeError.Type) { case "card_error": // Log Error details to your application Database // ex.StripeError.Code, ex.StripeError.Message, ex.StripeError.DocUrl, ex.StripeError.DeclineCode // Show a friendly message to the end user errorMessage.Text = "We are sorry, but we are unable to charge your credit card. Please ensure that " + "your credit card details are right and you have enough funds in it and try again."; break; case "api_connection_error": errorMessage.Text = "We are sorry but we couldn't charge your card. Please try again."; break; case "validation_error": errorMessage.Text = "We are sorry, but we are unable to charge your credit card. Please ensure that " + "your credit card details are right and you have enough funds in it and try again."; break; case "api_error": // 500 errors, very rare case "authentication_error": case "invalid_request_error": case "rate_limit_error": default: // Unknown Error Type errorMessage.Text = "We are sorry but we couldn't charge your card due to an issue on our end." + "Our engineers have been notified. Please wait for 24 hours and retry again. If the issue " + "isn't resovled still, then please call us on our customer care center at 1 800 123 1234."; break; } errorMessage.Visible = true; return; } #endregion #region Show success Message successMessage.Text = string.Format("<h4>Congratulations! We have successfully received your order.</h4>" + "<br/>Please save the Payment Intent ID {1} and the Charge ID {2} safely in case of a dispute.", int.Parse(hdnTotalPrice.Value), paymentIntentResult.Id, paymentIntentResult.Charges.FirstOrDefault().Id); successMessage.Visible = true; #endregion }