public void StripeCharge(string token, int amount) { var myCharge = new StripeChargeCreateOptions(); // always set these properties myCharge.Amount = amount; myCharge.Currency = "usd"; // set this if you want to myCharge.Description = "Digital Wallet fund"; // setting up the card myCharge.Source = new StripeSourceOptions() { // set this property if using a token TokenId = token }; // set this property if using a customer //myCharge.CustomerId = *customerId*; // set this if you have your own application fees (you must have your application configured first within Stripe) // myCharge.ApplicationFee = 25; // (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); }
public IActionResult CheckoutPayment(string StripeToken, string CustomerID, int ChargeAmount) { //var myCustomer = new StripeCustomerCreateOptions(); //myCustomer.Email = "*****@*****.**"; //myCustomer.Description = "Jonathan Tecson"; //myCustomer.SourceToken = StripeToken; ////myCustomer.TrialEnd = DateTime.UtcNow.AddMonths(1); // when the customers trial ends (overrides the plan if applicable) ////myCustomer.Quantity = 1; // optional, defaults to 1 //var customerService = new StripeCustomerService("sk_test_qFGjHTjY0gFwJsqkpskaiTLP"); //StripeCustomer stripeCustomer = customerService.Create(myCustomer); var StripeCharge = new StripeChargeCreateOptions(); StripeCharge.Amount = ChargeAmount; StripeCharge.Currency = "aud"; StripeCharge.Description = "Jupiter Subscription"; StripeCharge.SourceTokenOrExistingSourceId = StripeToken; StripeCharge.Capture = true; var StripeChargeService = new StripeChargeService("sk_test_qFGjHTjY0gFwJsqkpskaiTLP"); StripeCharge StripeChargeTrans = StripeChargeService.Create(StripeCharge); return(View()); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "post")] ChargeRequest req, [CosmosDB("store", "orders", ConnectionStringSetting = "CosmosDbConnectionString")] IAsyncCollector <StripeCharge> cosmosDbCollection, TraceWriter log) { log.Info("Order trigger function processed a request."); StripeConfiguration.SetApiKey("sk_test_BQokikJOvBiI2HlWgH4olfQ2"); // Creating the charge for the credit card var chargeOptions = new StripeChargeCreateOptions() { Amount = Convert.ToInt32(req.stripeAmt * 100), Currency = "usd", Description = $"Charge for {req.stripeEmail}", SourceTokenOrExistingSourceId = req.stripeToken }; // Charging the credit card StripeCharge charge = await chargeService.CreateAsync(chargeOptions); // Add to CosmosDb await cosmosDbCollection.AddAsync(charge); return(new OkResult()); }
public static async Task <StripeCharge> SendCharge(string stripeSecretApiKey, string cardToken, string currency, double amount, string description) { if (stripeSecretApiKey == null || stripeSecretApiKey == "") { throw new Exception("Error.InvalidPaymentApiKey"); } if (cardToken == null || cardToken == "") { throw new Exception("Error.InvalidPaymentCardToken"); } if (currency == null || (currency.ToLower() != "eur")) { throw new Exception("Error.InvalidPaymentCurrency"); } if (description == null || description == "") { throw new Exception("Error.InvalidPaymentDescription"); } StripeConfiguration.SetApiKey(stripeSecretApiKey); var chargeOptions = new StripeChargeCreateOptions() { Amount = (int)(amount * 100), Currency = currency, Description = description, SourceTokenOrExistingSourceId = cardToken // obtained with Stripe.js }; var chargeService = new StripeChargeService(); StripeCharge charge = await chargeService.CreateAsync(chargeOptions); return(charge); }
public StripeChargeServiceTest() { this.service = new StripeChargeService(); this.captureOptions = new StripeChargeCaptureOptions() { Amount = 123, }; this.createOptions = new StripeChargeCreateOptions() { Amount = 123, Currency = "usd", SourceTokenOrExistingSourceId = "tok_123", }; this.updateOptions = new StripeChargeUpdateOptions() { Metadata = new Dictionary <string, string>() { { "key", "value" }, }, }; this.listOptions = new StripeChargeListOptions() { Limit = 1, }; }
public OrderDto ChargeOrder(string stripeToken, OrderDto orderDto) { Order order = _orderDataProvider.GetOrderById(orderDto.OrderId); int amountToCharge = (int)(Math.Round(order.Amount, 2) * 100); int applicationFee = (int)(Math.Round(order.Amount, 1) * 10); var chargeOptions = new StripeChargeCreateOptions() { //required Amount = amountToCharge, Currency = "gbp", SourceTokenOrExistingSourceId = stripeToken, //optional Description = $"{order.User.Email} ordered {order.OrderDetails.SelectMany(x => x.ItemsPurchased).Count()} items from {order.Restaurant.Name}", ReceiptEmail = order.User.Email, //Add destination account and application fee to charge restaurant Destination = order.Restaurant.StripeAccountId, ApplicationFee = applicationFee }; ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; var chargeService = new StripeChargeService(); var stripeCharge = chargeService.Create(chargeOptions); order.OrderStatus = OrderStatus.Paid; order.PaymentStatus = OrderStatus.Paid; order.PaymentToken = stripeCharge.Id; _orderDataProvider.SaveOrder(order); return(Mapper.Map <OrderDto>(order)); }
public IActionResult Post([FromBody] PaymentModel payment) { // You can optionally create a customer first, attached this to patientID var charge = new StripeChargeCreateOptions { Amount = Convert.ToInt32(payment.Amount) * 100, //The default value is in cents, hence multply by 100 Currency = "ZAR", Description = "We Must bind the product details here", SourceTokenOrExistingSourceId = payment.Token }; var service = new StripeChargeService("sk-testxxxxxx");//api key try { //BONGA: I keep getting an error for the next line of code, will come back to it when we need to set up //var response = service.Capture(charge); //Record or do something with charge info } catch (StripeException ex) { StripeError stripeError = ex.StripeError; //handle error } return(OK(true));//will have to revisit this }
public async Task <Tuple <bool, string> > TryChargeUsingConnet(string customerId, string userId, int amount, string currency) { try { var applicationFeePercentage = Convert.ToInt32(ConfigurationManager.AppSettings["ApplicationFeePercentage"]); var applicationFee = (amount / 100) * applicationFeePercentage; var chargeCreateOptions = new StripeChargeCreateOptions { CustomerId = customerId, Amount = amount, Currency = currency, Destination = userId, ApplicationFee = applicationFee }; var chargeService = new StripeChargeService(); chargeService.Create(chargeCreateOptions); } catch (Exception exception) { return(Tuple.Create(false, exception.Message)); } return(Tuple.Create(true, "success!")); ; }
public when_creating_charges_with_multiple_expand() { var accountService = new StripeAccountService(Cache.ApiKey); var account = accountService.Create(new StripeAccountCreateOptions { Type = StripeAccountType.Custom }); var chargeOptions = new StripeChargeCreateOptions { SourceTokenOrExistingSourceId = "tok_visa", ApplicationFee = 10, Amount = 100, Currency = "usd", Destination = account.Id, }; chargeOptions.AddExpand("balance_transaction"); chargeOptions.AddExpand("transfer.balance_transaction.source"); chargeOptions.AddExpand("destination"); Charge = new StripeChargeService(Cache.ApiKey).Create(chargeOptions); accountService.Delete(account.Id); }
protected bool chargeCard(string tokenId, int amount) { var pinzeyCharge = new StripeChargeCreateOptions(); // always set these properties pinzeyCharge.Amount = amount; pinzeyCharge.Currency = "usd"; // set this if you want to pinzeyCharge.Description = "Charge it like it's hot"; // setting up the card pinzeyCharge.Source = new StripeSourceOptions() { // set this property if using a token TokenId = tokenId }; // set this if you have your own application fees (you must have your application configured first within Stripe) //myCharge.ApplicationFee = 25; // (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(pinzeyCharge); return(stripeCharge.Paid); }
public bool StripePay(string orderId, string stripeToken, string email) { var applicationManager = DomainHub.GetDomain <IApplicationManager>(); var order = applicationManager.GetOrder(orderId); var options = new StripeChargeCreateOptions { Amount = (int)(order.Amount * 100), Currency = EUR, SourceTokenOrExistingSourceId = stripeToken }; var service = new StripeChargeService(); var charge = service.Create(options); if (charge.Paid) { var payment = new DataAccess.Model.Storage.Payment { PartitionKey = orderId, ChargeId = charge.Id, RowKey = charge.Id, Time = DateTime.Now, Type = Stripe, Currency = charge.Currency, Amount = ((double)charge.Amount) / 100, Payer = charge.Customer?.Email ?? email }; PaymentTable.Insert(payment); } return(charge.Paid); }
protected void Button1_Click(object sender, EventArgs e) { try { StripeCustomer current = GetCustomer(); // int? days = getaTraildays(); //if (days != null) //{ int chargetotal = 500;//Convert.ToInt32((3.33*Convert.ToInt32(days)*100)); var mycharge = new StripeChargeCreateOptions(); mycharge.Amount = chargetotal; mycharge.Currency = "USD"; mycharge.CustomerId = current.Id; string key = "sk_test_5jzcBuYhyxAk08sB8mT7KL43"; var chargeservice = new StripeChargeService(key); StripeCharge currentcharge = chargeservice.Create(mycharge); error.Visible = true; error.InnerText = "La transacción se realizo con éxito"; } catch (StripeException ex) { error.Visible = true; error.InnerText = ex.Message; } catch { error.Visible = true; error.InnerText = "Error en la transacción"; } //} }
public static bool Charge(Customer customer, CreditCard creditCard, decimal amount) { var chargeDetails = new StripeChargeCreateOptions(); chargeDetails.Amount = (int)amount * 100; chargeDetails.Currency = "usd"; chargeDetails.Source = new StripeSourceOptions { Object = "card", Number = creditCard.CardNumber, ExpirationMonth = creditCard.ExpireyDate.Month.ToString(), ExpirationYear = creditCard.ExpireyDate.Year.ToString(), Cvc = creditCard.Cvc, }; var chargeService = new StripeChargeService(StripeApiKey); var response = chargeService.Create(chargeDetails); if (response.Paid == false) { throw new Exception(response.FailureMessage); } return(response.Paid); }
private String ChargeCard(String token) { var myCharge = new StripeChargeCreateOptions(); // always set these properties myCharge.Amount = (User.IsInRole("BasicUser") || User.IsInRole("Admin") || User.IsInRole("ProfileUser")) ? 19900 : User.IsInRole("ArchiveUser") ? 14900 : 19900; myCharge.Currency = "usd"; // set this if you want to myCharge.Description = "Embracing Memories - New Profile"; myCharge.SourceTokenOrExistingSourceId = token; // set this property if using a customer - this MUST be set if you are using an existing source! //myCharge.CustomerId = *customerId *; // set this if you have your own application fees (you must have your application configured first within Stripe) //myCharge.ApplicationFee = 25; // (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(); try { StripeCharge stripeCharge = chargeService.Create(myCharge); } catch (Exception ex) { return(ex.Message); } return(null); }
public IActionResult orderstatus(string stripeToken, string address, string cardholdername, double amount, string description) { var myCharge = new StripeChargeCreateOptions(); // when the customers trial ends (overrides the plan if applicable) // always set these properties myCharge.Amount = (int)(amount * 100); myCharge.Currency = "usd"; // set this if you want to myCharge.Description = description; myCharge.SourceTokenOrExistingSourceId = stripeToken; // set this property if using a customer - this MUST be set if you are using an existing source! // (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); if (stripeCharge.Status == "succeeded") { return(View()); } return(RedirectToAction("orders")); }
public ActionResult Index(FormCollection tokenString) { if (tokenString == null) { return(View("SecurePayment")); } else { try { var myCharge = new StripeChargeCreateOptions(); // always set these properties myCharge.Amount = 120; myCharge.Currency = "eur"; // set this if you want to myCharge.Description = "Charge it like it's hot"; // setting up the card myCharge.Source = new StripeSourceOptions() { // set this property if using a token TokenId = tokenString[0], // set these properties if passing full card details (do not // set these properties if you set TokenId) //Number = "4242424242424242", //ExpirationYear = "2022", //ExpirationMonth = "10", //AddressCountry = "US", // optional //AddressLine1 = "24 Beef Flank St", // optional //AddressLine2 = "Apt 24", // optional //AddressCity = "Biggie Smalls", // optional //AddressState = "NC", // optional //AddressZip = "27617", // optional //Name = "Joe Meatballs", // optional //Cvc = "1223" // optional }; // set this property if using a customer //myCharge.CustomerId = *customerId*; // set this if you have your own application fees (you must have your application configured first within Stripe) //myCharge.ApplicationFee = 25; // (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); return(View("PaymentSuccess")); } catch { return(View("SecurePayment")); } } }
/// <summary> /// Create Charge with customer /// </summary> /// <param name="creditCard"></param> /// <returns></returns> public async Task <StripeCharge> ChargeCardAsync(CreditCardModel creditCard, Citation citation, CommonAccount account, ChargeTypeEnum chargeType) { Check.NotNull(creditCard, nameof(creditCard)); var metaData = new Dictionary <string, string>(); metaData["Account"] = account.Name; metaData["AccountNumber"] = account.Number.ToString(); metaData["CitationNumber"] = citation.CitationNumber.ToString(); metaData["Type"] = chargeType.GetDescription(); // Token is created using Checkout or Elements! // Get the payment token submitted by the form: var token = creditCard.SourceToken; // Using ASP.NET MVC var options = new StripeChargeCreateOptions { Amount = creditCard.Amount, Currency = "usd", Description = chargeType.GetDescription(), SourceTokenOrExistingSourceId = token, Metadata = metaData }; var service = new StripeChargeService(); StripeCharge charge = await service.CreateAsync(options); return(charge); }
private async Task <string> ProcessPayment(StripeChargeModel model) { //TODO if (model.Amount == 0) { model.Amount = 1900; } model.Card.TokenId = model.Id; return(await Task.Run(() => { var myCharge = new StripeChargeCreateOptions { // convert the amount of £12.50 to pennies i.e. 1250 Amount = model.Amount, //in pence Currency = "gbp", Description = "Charged £19 one-off up to 1000", Card = model.Card, ReceiptEmail = model.Email // TokenId = model.Token }; var chargeService = new StripeChargeService(ConfigurationManager.AppSettings["StripeApiKey"]); var stripeCharge = chargeService.Create(myCharge); return stripeCharge.Id; })); }
public StripeCharge CreateTransaction(string advertiserId, int totalAmount, int platformCharge, string influencerAccId) { StripeConfiguration.SetApiKey(""); // direct charge from advertiser & deposit in influencer account // https://stripe.com/docs/connect/direct-charges // https://gist.github.com/jaymedavis/d969be13ca6019686a4e72b82e999546 // Charge the Customer instead of the card var chargeOptions = new StripeChargeCreateOptions { Amount = totalAmount, Currency = "usd", CustomerId = advertiserId, ApplicationFee = platformCharge }; var requestOptions = new StripeRequestOptions(); requestOptions.StripeConnectAccountId = influencerAccId; var chargeService = new StripeChargeService(); StripeCharge charge = chargeService.Create(chargeOptions, requestOptions); return(charge); }
private void BuyAService(UserService servicoToHire, HireServiceModel payer) { var customer = CreateOrRetrieveAccountCustomer(payer); var finalPrice = PriceManager.FinalPrice(servicoToHire); var valueToPay = Int32.Parse(finalPrice.ToString() .Replace(",", string.Empty) .Replace(".", string.Empty)); // Recebendo o dinheiro. var chargeOptions = new StripeChargeCreateOptions() { Amount = valueToPay, Currency = "brl", Description = servicoToHire.Name, CustomerId = customer.Id, TransferGroup = "{ORDER10}", }; var chargeService = new StripeChargeService(); PaymentsCustomer payment = new PaymentsCustomer { Customer = customer, Amount = valueToPay, PayDay = DateTime.Now }; IlevusDBContext db = IlevusDBContext.Create(); db.GetPaymentsCustomerCollection().InsertOne(payment); }
private IHttpActionResult StripeCheckout(ChargeDtos charge) { try { var customer = _customers.Create(new StripeCustomerCreateOptions { Email = charge.Email, SourceToken = charge.Token }); var chargeOptions = new StripeChargeCreateOptions() { Amount = charge.Amount, Currency = "usd", Description = "Charge for " + charge.Email ?? charge.Name, CustomerId = customer.Id, SourceTokenOrExistingSourceId = charge.Token // obtained with Stripe.js }; var stripeCharge = _charges.Create(chargeOptions); return(Ok()); } catch (Exception) { return(StatusCode(HttpStatusCode.InternalServerError)); } }
public async Task <StripeCharge> CreateChargeAsync(StripeChargeCreateOptions options, string apiKey) { var chargeService = new StripeChargeService(apiKey); var charge = chargeService.Create(options); return(charge); }
public async void StripeProcess(string Token) { var charge = new StripeChargeCreateOptions { Amount = Convert.ToInt32(Total * 100), // In cents, not dollars, times by 100 to convert Currency = "usd", // or the currency you are dealing with Description = "StadiYUM Order", SourceTokenOrExistingSourceId = "tok_visa" }; var service = new StripeChargeService("sk_test_fMQSO85L4eNQWH7LEESCbY71"); try { var response = service.Create(charge); if (response.Paid) { manager.CartFinished(); await DisplayAlert("Order Confirmed", "Go to Orders to view status", "OK"); } // Record or do something with the charge information } catch (StripeException ex) { StripeError stripeError = ex.StripeError; DisplayAlert("Error", stripeError.Error, "OK"); // Handle error } // Ideally you would put in additional information, but you can just return true or false for the moment. }
private async Task <string> ProcessPayment(StripeChargeModel model) { //StripeConfiguration.SetApiKey("pk_test_ZwQQ3DpHRcIWDMKgVObfuSYl"); return(await Task.Run(() => { var myCharge = new StripeChargeCreateOptions { Amount = (int)(model.Amount * 1), Currency = "gbp", Description = "Description for test charge", // SourceTokenOrExistingSourceId = model.Token }; try { var chargeService = new StripeChargeService("sk_test_sunSx6HuXZrAcIp2W8k7L4zk"); var stripeCharge = chargeService.Create(myCharge); return stripeCharge.Id; } catch (Exception e) { Response.Write("<script>alert('Data Saved succesfully in Database but further transaction process you must provide Cutomer or merchant.')</script>"); return e.Message; } })); }
//Collect single charge for coupon //public static bool Charge(string stripeToken, Offer offer) //{ // StripeConfiguration.SetApiKey(WebConfigurationManager.AppSettings["StripeSecretKey"]); // var token = stripeToken; // var loginUser = _context.Merchants.Include(c => c.User).FirstOrDefault(c => c.MerchantID == offer.MerchantID); // //Create stripe customerID // var customerId = CreateStripeCustomer(loginUser.User.Id, token); // var option = new StripeChargeCreateOptions // { // Amount = Convert.ToInt32(offer.CouponPrice * 100), // Currency = "usd", // Description = "Veme", // ReceiptEmail = loginUser.User.Email, // returns the email address // //SourceTokenOrExistingSourceId = token, // CustomerId = customerId // }; // var service = new StripeChargeService(); // StripeCharge charge = service.Create(option); // //if (charge.Paid) // //return Json(new { charge.Paid}); // return charge.Paid; //} public async static Task <bool> Charge(string stripeToken, CouponValidationPackage package, string MerchantId) { StripeConfiguration.SetApiKey(WebConfigurationManager.AppSettings["StripeSecretKey"]); var token = stripeToken; var loginUser = _context.Merchants.Include(c => c.User).FirstOrDefault(c => c.MerchantID == MerchantId); //Create stripe customerID //var customerId = CreateStripeCustomer(loginUser.User.Id, token); var option = new StripeChargeCreateOptions { Amount = Convert.ToInt32(package.PackagePrice * 100), Currency = "usd", Description = "Veme - " + package.PackageName, ReceiptEmail = loginUser.User.Email, // returns the email address SourceTokenOrExistingSourceId = token, Capture = true, }; var service = new StripeChargeService(); StripeCharge charge = service.Create(option); //Assign Package to Merchant if charge successful if (charge.Paid) { await Payment.AssignPackage(package.Id, loginUser.MerchantID); } //return Json(new { charge.Paid}); return(charge.Paid); }
public async Task WhenThrowsExceptionDuringCreateCharge_ItShouldWrapAndPropagateException() { this.apiKeyRepository.Setup(v => v.GetApiKey(UserType.TestUser)).Returns(TestKey); var expectedOptions = new StripeChargeCreateOptions { Amount = Amount.Value, Currency = PerformStripeCharge.Currency, CustomerId = StripeCustomerId, Metadata = new Dictionary <string, string> { { PerformStripeCharge.TransactionReferenceMetadataKey, TransactionReference.ToString() }, { PerformStripeCharge.TaxamoTransactionKeyMetadataKey, TaxamoTransactionKey }, { PerformStripeCharge.UserIdMetadataKey, UserId.ToString() }, } }; this.stripeService.Setup(v => v.CreateChargeAsync( It.Is <StripeChargeCreateOptions>( x => JsonConvert.SerializeObject(x, Formatting.None) == JsonConvert.SerializeObject(expectedOptions, Formatting.None)), TestKey)) .Throws(new DivideByZeroException()); await ExpectedException.AssertExceptionAsync <StripeChargeFailedException>( () => this.target.ExecuteAsync(StripeCustomerId, Amount, UserId, TransactionReference, TaxamoTransactionKey, UserType.TestUser)); }
public void TestCharge() { StripeSDKMain stripe = new StripeSDKMain(); StripeChargeCreateOptions stripeChargeCreateOptions = new StripeChargeCreateOptions(); stripeChargeCreateOptions.Amount = 3000; stripeChargeCreateOptions.Currency = "usd"; stripeChargeCreateOptions.SourceTokenOrExistingSourceId = "tok_amex"; Serializer serializer = new Serializer(); var stripeChargeCreateOptionsJSON = serializer.Serialize <StripeChargeCreateOptions>(stripeChargeCreateOptions); string Response = ""; string Errors = ""; int ErrorCode = 0; var Api_Key = GetApiKey(); stripe.CreateCharge(Api_Key, stripeChargeCreateOptionsJSON, ref Response, ref Errors, ref ErrorCode); if (ErrorCode == 0) { Console.WriteLine(Response); } else { Console.WriteLine(Errors); } }
public async Task WhenStripeModeIsTest_ItShouldCreateACharge() { this.apiKeyRepository.Setup(v => v.GetApiKey(UserType.TestUser)).Returns(TestKey); var expectedOptions = new StripeChargeCreateOptions { Amount = Amount.Value, Currency = PerformStripeCharge.Currency, CustomerId = StripeCustomerId, Metadata = new Dictionary <string, string> { { PerformStripeCharge.TransactionReferenceMetadataKey, TransactionReference.Value.ToString() }, { PerformStripeCharge.TaxamoTransactionKeyMetadataKey, TaxamoTransactionKey }, { PerformStripeCharge.UserIdMetadataKey, UserId.ToString() }, } }; var charge = new StripeCharge { Id = ChargeId }; this.stripeService.Setup(v => v.CreateChargeAsync( It.Is <StripeChargeCreateOptions>( x => JsonConvert.SerializeObject(x, Formatting.None) == JsonConvert.SerializeObject(expectedOptions, Formatting.None)), TestKey)) .ReturnsAsync(charge); var result = await this.target.ExecuteAsync(StripeCustomerId, Amount, UserId, TransactionReference, TaxamoTransactionKey, UserType.TestUser); Assert.AreEqual(ChargeId, result); }
/// <summary> /// Creates the charge. /// </summary> /// <param name="t">The t.</param> /// <param name="capture"> /// Whether or not to immediately capture the charge. When false, the charge issues an /// authorization(or pre-authorization), and will need to be captured later /// </param> private void CreateCharge(Transaction t, bool capture) { StripeConfiguration.SetApiKey(Settings.StripeApiKey); var chargeOptions = new StripeChargeCreateOptions(); // always set these properties chargeOptions.Amount = (int)(t.Amount * 100); chargeOptions.Currency = Settings.CurrencyCode; // set this if you want to chargeOptions.Capture = capture; chargeOptions.Currency = Settings.CurrencyCode; chargeOptions.Description = t.MerchantDescription; chargeOptions.Source = new StripeSourceOptions(); // set these properties if using a card chargeOptions.Source.Number = t.Card.CardNumber; chargeOptions.Source.ExpirationYear = t.Card.ExpirationYear.ToString(); chargeOptions.Source.ExpirationMonth = t.Card.ExpirationMonthPadded; //myCharge.CardAddressCountry = "US"; // optional if (t.Customer.Street.Length > 0) { chargeOptions.Source.AddressLine1 = t.Customer.Street; // optional } //myCharge.CardAddressLine2 = "Apt 24"; // optional //myCharge.CardAddressState = "NC"; // optional if (t.Customer.PostalCode.Length > 0) { chargeOptions.Source.AddressZip = t.Customer.PostalCode; // optional } chargeOptions.Source.Name = t.Card.CardHolderName; // optional if (!string.IsNullOrEmpty(t.Card.SecurityCode)) { chargeOptions.Source.Cvc = t.Card.SecurityCode; // optional } // set this property if using a customer //myCharge.CustomerId = *customerId*; // set this property if using a token //myCharge.TokenId = *tokenId*; var chargeService = new StripeChargeService(); var stripeCharge = chargeService.Create(chargeOptions); if (stripeCharge.Id.Length > 0 && stripeCharge.Amount > 0) { t.Result.Succeeded = true; t.Result.ReferenceNumber = stripeCharge.Id; } else { t.Result.Succeeded = false; t.Result.ResponseCode = "FAIL"; t.Result.ResponseCodeDescription = "Stripe Failure"; } }
public async Task <bool> ChargeCustomer(string tokenId, int amount) { return(await System.Threading.Tasks.Task.Run(() => { try { var myCharge = new StripeChargeCreateOptions { Amount = amount, Currency = "usd", Description = "Fund Digital Wallet", Source = new StripeSourceOptions() { TokenId = tokenId }, Capture = true, }; var chargeService = new StripeChargeService(); var stripeCharge = chargeService.Create(myCharge); if (stripeCharge.Status == "succeeded" && stripeCharge.Paid == true) { return true; } return false; } catch (Exception) { //log exception here return false; } })); }