Beispiel #1
0
        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());
        }
Beispiel #2
0
        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);
        }
        /// <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);
        }
Beispiel #4
0
        public async Task <IActionResult> Create([FromBody] CreateOrderViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = await _db.Users.SingleAsync(x => x.UserName == HttpContext.User.Identity.Name);

            var order = new Order {
                DeliveryAddress = new Address {
                    FirstName = model.FirstName,
                    LastName  = model.LastName,
                    Address1  = model.Address1,
                    Address2  = model.Address2,
                    TownCity  = model.TownCity,
                    County    = model.County,
                    Postcode  = model.Postcode
                },
                Items = model.Items.Select(x => new OrderItem {
                    ProductId = x.ProductId,
                    ColourId  = x.ColourId,
                    StorageId = x.StorageId,
                    Quantity  = x.Quantity
                }).ToList()
            };

            user.Orders.Add(order);

            await _db.SaveChangesAsync();

            var total = await _db.Orders
                        .Where(x => x.Id == order.Id)
                        .Select(x => Convert.ToInt32(x.Items.Sum(i => i.ProductVariant.Price * i.Quantity) * 100))
                        .SingleAsync();

            var charges = new StripeChargeService();
            var charge  = await charges.CreateAsync(new StripeChargeCreateOptions {
                Amount      = total,
                Description = $"Order {order.Id} payment",
                Currency    = "GBP",
                SourceTokenOrExistingSourceId = model.StripeToken
            });

            if (string.IsNullOrEmpty(charge.FailureCode))
            {
                order.PaymentStatus = PaymentStatus.Paid;
            }
            else
            {
                order.PaymentStatus = PaymentStatus.Declined;
            }

            await _db.SaveChangesAsync();

            return(Ok(new CreateOrderResponseViewModel(order.Id, order.PaymentStatus)));
        }
 public async Task ChargeCustomer(Domain.Order order, StripeToken token)
 {
     var options = new StripeChargeCreateOptions {
         Amount      = (int)(order.TotalAmount * 100m),
         Currency    = "nok",
         Description = order.Registration.EventInfo.Title,
         SourceTokenOrExistingSourceId = token.Id,
         ReceiptEmail = order.CustomerEmail
     };
     var          service = new StripeChargeService();
     StripeCharge charge  = await service.CreateAsync(options);
 }
Beispiel #6
0
        public async Task <string> ProcessPaymentByToken(double total, string paymentToken)
        {
            var chargeService = new StripeChargeService(this.stripeSecretKey);

            var charge = new StripeChargeCreateOptions
            {
                SourceTokenOrExistingSourceId = paymentToken,
                Amount   = (int)(total * 100),
                Currency = "CAD"
            };

            var response = await chargeService.CreateAsync(charge);

            return(response.Id);
        }
Beispiel #7
0
        public async Task <string> ProcessPaymentByCustomerId(double total, string customerId)
        {
            var chargeService = new StripeChargeService(this.stripeSecretKey);

            var charge = new StripeChargeCreateOptions
            {
                Amount     = (int)(total * 100),
                Currency   = "CAD",
                CustomerId = customerId
            };

            var response = await chargeService.CreateAsync(charge);

            return(response.Id);
        }
        private async Task <StripeCharge> _CreateCharge(
            int amount,
            string currency,
            string customer_id,
            string description
            )
        {
            var charges = new StripeChargeService();

            var charge = await charges.CreateAsync(new StripeChargeCreateOptions
            {
                Amount      = amount,
                Currency    = currency,
                CustomerId  = customer_id,
                Description = description
            });

            return(charge);
        }
Beispiel #9
0
        public async Task <string> ExecuteTransaction(string stripeToken, string stripeSecretKey, int amount)
        {
            var chargeOptions = new StripeChargeCreateOptions()
            {
                Amount   = amount,
                Currency = "AUD",
                SourceTokenOrExistingSourceId = stripeToken
            };

            var client = new StripeChargeService(stripeSecretKey);
            var result = await client.CreateAsync(chargeOptions);

            if (!result.Paid)
            {
                throw new Exception(result.FailureMessage);
            }

            return(result.Id);
        }
Beispiel #10
0
        public async Task <IActionResult> ChargeAsync([FromServices] StripeConfiguration configuration, [FromBody] ChargeBindings bindings, CancellationToken cancellationToken = default(CancellationToken))
        {
            var order = await this.orderService.GetByIdAsync(bindings.OrderID, cancellationToken);

            var requestOptions = new StripeRequestOptions {
                ApiKey = configuration.SecretKey
            };

            var customers = new StripeCustomerService();
            var charges   = new StripeChargeService();
            var payment   = new Payment()
            {
                Title     = "Stripe Payment",
                Provider  = Name,
                Reference = $"{bindings.Token}",
                Status    = PaymentStatus.Paid,
                Date      = DateTime.UtcNow,
                Method    = PaymentMethod.Electronic,
                Details   = $"Payment Order #{order.Reference}",
                Currency  = order.Currency,
                Amount    = bindings.Amount
            };


            var customer = await customers.CreateAsync(new StripeCustomerCreateOptions
            {
                SourceToken = bindings.Token
            }, requestOptions, cancellationToken : cancellationToken);



            var charge = await charges.CreateAsync(new StripeChargeCreateOptions
            {
                Amount      = Convert.ToInt32(payment.Amount * 100),
                Description = payment.Details,
                Currency    = payment.Currency,
                CustomerId  = customer.Id
            }, requestOptions, cancellationToken : cancellationToken);

            await orderService.AddPayment(order, payment, cancellationToken);

            return(Ok(ApiModel.AsSuccess(order)));
        }
        async Task <InforAutosStripeCharge> ICustomStripeService.MakePayment(StripeCardInfo cardInfo, double Amount)
        {
            //var _token  = CreateToken(cardInfo.CardNumber, cardInfo.Month, cardInfo.Year, cardInfo.CCV);
            InforAutosStripeCharge result = new InforAutosStripeCharge();

            try
            {
                var myCharge = new StripeChargeCreateOptions();
                var myToken  = new StripeTokenCreateOptions();
                myToken.Card = new StripeCreditCardOptions()
                {
                    Number          = cardInfo.CardNumber,
                    ExpirationMonth = cardInfo.Month,
                    ExpirationYear  = cardInfo.Year,
                    Cvc             = cardInfo.CCV
                };
                // Stripe amount transformation from double with 2 decimals
                //Amount = 1;
                myCharge.Amount = Int32.Parse((Amount * Int32.Parse("100")).ToString());

                myCharge.Currency = "EUR";
                var chargeService = new StripeChargeService(API_KEY);
                var tokenService  = new StripeTokenService(API_KEY);
                var token         = tokenService.Create(myToken);
                myCharge.SourceTokenOrExistingSourceId = token.Id;
                StripeCharge stripeCharge = await chargeService.CreateAsync(myCharge);

                result.FailureMessage = stripeCharge.FailureMessage;
                result.IsPaid         = stripeCharge.Paid;
                result.ID             = stripeCharge.Id;
            }
            catch (System.Exception ex)
            {
                // result.FailureMessage = "Payment Successful";
                result.FailureMessage = ex.Message;
            }

            return(result);
        }
Beispiel #12
0
        public async Task <bool> ProcessPayment(string customerToken, int amount, string email, string description)
        {
            var chargeService = new StripeChargeService();

            try
            {
                var charge = await chargeService.CreateAsync(new StripeChargeCreateOptions
                {
                    Amount       = amount,
                    Description  = description,
                    Currency     = "GBP",
                    CustomerId   = customerToken,
                    ReceiptEmail = email
                });
            }
            catch (StripeException e)
            {
                if (e.StripeError.ErrorType == "card_error")
                {
                    return(false);
                }
            }
            return(true);
        }