Exemplo n.º 1
0
        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);
        }
Exemplo n.º 2
0
        public static bool Charge(Customer cus, CreditCard cc, decimal amount) //PRD)
        {
            var chargeDetails = new StripeChargeCreateOptions();
            chargeDetails.Amount = (int)amount * 100;
            chargeDetails.Currency = "usd";

            chargeDetails.Source = new StripeSourceOptions
            {
                Object = "card",
                Number = cc.CardNum,
                ExpirationMonth = cc.Expiration.Substring(0, 2),
                ExpirationYear = cc.Expiration.Substring(3, 2),
                Cvc = cc.CVC
            };

            var chargeService = new StripeChargeService(APIKey);
            var response = chargeService.Create(chargeDetails);

            if (response.Paid == false)
            {
                throw new Exception(response.FailureMessage);
            }

            return response.Paid;

        }
Exemplo n.º 3
0
        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;
        }
Exemplo n.º 4
0
        public ActionResult Charge([FromBody]string stripeEmail, string stripeToken)
        {
            try
            {
                var charge = new StripeChargeCreateOptions()
                {
                    Amount = _settings.StripeDonationAmountInCents,
                    Currency = _settings.StripeDonationCurrency,
                    Description = "Donation for An API of Ice And Fire",
                    ReceiptEmail = stripeEmail,
                    Source = new StripeSourceOptions
                    {
                        TokenId = stripeToken
                    }
                };

                var chargeService = new StripeChargeService(_settings.StripePrivateKey);
                chargeService.Create(charge);
            }
            catch (StripeException se)
            {
                //Log error in a better way later on
                Debug.WriteLine(se.StripeError);
            }

            return Redirect("/");
        }
Exemplo n.º 5
0
        public static bool Charge(Customer customer, CreditCard creditcard, decimal amount)
        {
            var myCharge = new StripeChargeCreateOptions();

            // always set these properties
            myCharge.Amount = (int)amount*100;
            myCharge.Currency = "usd";

            // setting up the card
            myCharge.Source = new StripeSourceOptions()
            {
                Object = "card",
                Number = creditcard.creditCardNumber,
                ExpirationMonth = creditcard.expiryDateMonth,
                ExpirationYear = creditcard.expiryDateYear,
                Cvc = creditcard.securityCode                          // optional
            };
            
            var chargeService = new StripeChargeService(StripeApiKey);
            StripeCharge apiResponse = chargeService.Create(myCharge);

            if(apiResponse.Paid == false)
            {
                throw new Exception(apiResponse.FailureMessage);
            }


           
            return apiResponse.Paid;
          


        }
Exemplo n.º 6
0
        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.ExpirationDate.Month.ToString(),
                ExpirationYear = creditCard.ExpirationDate.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 async Task<string> ProcessPayment(CourseRegistrationModel model, int id)
        {
            var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
            var currentUser = manager.FindById(User.Identity.GetUserId());
            string userEmail = currentUser.Email;
            return await Task.Run(() =>
            {
                Course course = db.Courses.Find(id);
                var myCharge = new StripeChargeCreateOptions
                {
                    Amount = (int)(course.Course_Cost * model.NumberOfParticipants * 100),
                    Currency = "usd",
                    Description = "Description for test charge",
                    ReceiptEmail = userEmail,
                    Source = new StripeSourceOptions
                    {
                        TokenId = model.Token
                    }
                };

                var chargeService = new StripeChargeService("sk_test_yPi2XADkAP3wiS1i6tkjErxZ");
                var stripeCharge = chargeService.Create(myCharge);

                return stripeCharge.Id;
            });
        }
        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");
                }
            }
        }
        public ActionResult Custom(CustomViewModel customViewModel)
        {
            customViewModel.PaymentFormHidden = false;
            var chargeOptions = new StripeChargeCreateOptions()
            {
                //required
                Amount = 3900,
                Currency = "usd",
                Source = new StripeSourceOptions() {TokenId= customViewModel.StripeToken},
                //optional
                Description = string.Format("JavaScript Framework Guide Ebook for {0}", customViewModel.StripeEmail),
                ReceiptEmail = customViewModel.StripeEmail
            };

            var chargeService = new StripeChargeService();

            try
            {
                var stripeCharge = chargeService.Create(chargeOptions);
            }
            catch (StripeException stripeException)
            {
                Debug.WriteLine(stripeException.Message);
                ModelState.AddModelError(string.Empty, stripeException.Message);
                return View(customViewModel);
            }

            return RedirectToAction("Confirmation");
        }
Exemplo n.º 10
0
        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;
                }
            });
        }
Exemplo n.º 11
0
        private void CreateCharge(Transaction t)
        {
            Stripe.Configuration.SetApiKey(Settings.StripeApiKey);

            var myCharge = new StripeChargeCreateOptions();
            
            // always set these properties
            myCharge.AmountInCents = (int)(t.Amount * 100);
            myCharge.Currency = Settings.CurrencyCode;
            
            // set this if you want to
            myCharge.Description = t.MerchantDescription;
            
            // set these properties if using a card
            myCharge.CardNumber = t.Card.CardNumber;
            myCharge.CardExpirationYear = t.Card.ExpirationYear.ToString();
            myCharge.CardExpirationMonth = t.Card.ExpirationMonthPadded;
            //myCharge.CardAddressCountry = "US";             // optional
            if (t.Customer.Street.Length > 0) myCharge.CardAddressLine1 = t.Customer.Street; // optional
            //myCharge.CardAddressLine2 = "Apt 24";           // optional
            //myCharge.CardAddressState = "NC";               // optional
            if (t.Customer.PostalCode.Length > 0) myCharge.CardAddressZip = t.Customer.PostalCode; // optional
            myCharge.CardName = t.Card.CardHolderName;      // optional
            if (t.Card.SecurityCode.Length > 0)
            {
                myCharge.CardCvc = 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();
            
            StripeCharge stripeCharge = chargeService.Create(myCharge);

            if (stripeCharge.Id.Length > 0 &&
                stripeCharge.AmountInCents.HasValue && stripeCharge.AmountInCents > 0)
            {
                t.Result.Succeeded = true;
                t.Result.ReferenceNumber = stripeCharge.Id;
            }
            else
            {
                    
            }
            {
                t.Result.Succeeded = false;
                t.Result.ResponseCode = "FAIL";
                t.Result.ResponseCodeDescription = "Stripe Failure";
            }
            
        }
Exemplo n.º 12
0
        protected void Page_Load(object sender, EventArgs e)
        {

            #region Working....

            var myCharge = new StripeChargeCreateOptions
            {
                Amount =(int) (29.99 *100),
                Currency = "usd",
                Description = "Charge it like it's hot 2",
                Source = new StripeSourceOptions()
                {
                    // set this property if using a token


                    // set these properties if passing full card details (do not
                    // set these properties if you set TokenId)
                    Object = "card",
                    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 2", // optional
                    Cvc = "1223" // optional
                },
                //ApplicationFee = 25,
                Capture = true
            };

            // always set these properties

            // set this if you want to

            // setting up the card

            //set this property if using a customer
            //myCharge.CustomerId = "postman2021";

            // set this if you have your own application fees (you must have your application configured first within Stripe)

            // (not required) set this to false if you don't want to capture the charge yet - requires you call capture later

            var chargeService = new StripeChargeService(ConfigurationManager.AppSettings["StripeApiKey"]);
            var stripeCharge = chargeService.Create(myCharge);
            

            #endregion Working....
        }
Exemplo n.º 13
0
        public ActionResult Custom(CustomViewModel customViewModel)
        {
            customViewModel.PaymentFormHidden = false;
            var chargeOptions = new StripeChargeCreateOptions()
            {
                //required
                Amount = 3900,
                Currency = "usd",
                Source = new StripeSourceOptions() { TokenId = customViewModel.StripeToken },
                //optional
                Description = string.Format("JavaScript Framework Guide Ebook for {0}", customViewModel.StripeEmail),
                ReceiptEmail = customViewModel.StripeEmail
            };

            var chargeService = new StripeChargeService();

            try
            {
                StripeCharge stripeCharge = chargeService.Create(chargeOptions);

                //Validate charge
                chargeService.Capture(stripeCharge.Id);

                if (stripeCharge.Status == "succeeded")
                {
                    //creating the customer and add it to stripe
                    var newCustomer = new StripeCustomerService().Create(
                        new StripeCustomerCreateOptions
                        {
                            Email = customViewModel.StripeEmail
                        }
                        );
                    // CREATE NEW INVOICE
                    // var invoiceService = new StripeInvoiceService();
                    // StripeInvoice response = invoiceService.Create(newCustomer.Id); // optional StripeInvoiceCreateOptions
                    //var response = invoiceService.Upcoming(newCustomer.Id);
                    // stripeCharge.InvoiceId = response.Id;

                    //SEND THE CONFIRMATION
                    var emailService = new EmailService();
                    emailService.SendPaymentReceivedFromChargeEmail(stripeCharge);

                }
            }
            catch (StripeException stripeException)
            {
                Debug.WriteLine(stripeException.Message);
                ModelState.AddModelError(string.Empty, stripeException.Message);
                return View(customViewModel);
            }

            return RedirectToAction("Confirmation");
        }
        public HttpResponseMessage Post(StripeOrderDto order)
        {
            var confirmationNumber = GetConfirmationNumber();

            var charge = new StripeChargeCreateOptions
            {
                Amount = 2999,
                Currency = "usd",
                Description = "Test",
                SourceTokenOrExistingSourceId = order.StripeToken,
                Capture = true
            };

            var chargeService = new StripeChargeService();
            var stripeCharge = chargeService.Create(charge);

            var orderEntity = new Order()
            {
                ConfirmationNumber = confirmationNumber,
                BillingAddressCity = order.StripeBillingAddressCity,
                BillingAddressCountry = order.StripeBillingAddressCountry,
                BillingAddressCountryCode = order.StripeBillingAddressCountryCode,
                BillingAddressLine1 = order.StripeBillingAddressLine1,
                BillingAddressLine2 = order.StripeBillingAddressLine2,
                BillingAddressState = order.StripeBillingAddressState,
                BillingAddressZip = order.StripeBillingAddressZip,
                BillingName = order.StripeBillingName,
                Email = order.StripeEmail,
                Fulfilled = false,
                ShippingAddressCity = order.StripeShippingAddressCity,
                ShippingAddressCountry = order.StripeShippingAddressCountry,
                ShippingAddressCountryCode = order.StripeShippingAddressCountryCode,
                ShippingAddressLine1 = order.StripeShippingAddressLine1,
                ShippingAddressLine2 = order.StripeShippingAddressLine2,
                ShippingAddressState = order.StripeShippingAddressState,
                ShippingAddressZip = order.StripeShippingAddressZip,
                ShippingName = order.StripeShippingName,
                Token = stripeCharge.Id
            };

            _orderRepository.Insert(orderEntity);

            var response = Request.CreateResponse(HttpStatusCode.Moved);
            var uri = Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.AbsolutePath, "/Confirmation/Details/" + confirmationNumber);
            response.Headers.Location = new Uri(uri);
            return response;
        }
        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;
        }
        public ActionResult Index(HomeViewModel model)
        {
            // Stripe charge logic
            StripeChargeService chargeService = new StripeChargeService(AppConfig.stripePrivateKey);
            StripeChargeCreateOptions myCharge = new StripeChargeCreateOptions()
            {
                Currency = "aud",
                Description = model.cardDetails.description,
                Amount = model.cardDetails.price,
                Source = new StripeSourceOptions()
                {
                    TokenId = model.cardDetails.stripeToken
                }
            };
            StripeCharge stripeCharge = chargeService.Create(myCharge);

            model.transactions = GetTransactions();

            return View(model);
        }
Exemplo n.º 17
0
        private async Task<string> ProcessPayment(StripeChargeModel model)
        {
            return await Task.Run(() =>
            {
                var myCharge = new StripeChargeCreateOptions
                {
                    // convert the amount of £12.50 to pennies i.e. 1250
                    Amount = (int)(model.Amount * 100),
                    Currency = "gbp",
                    Description = "Description for test charge",
                    Source = new StripeSourceOptions{
                        TokenId = model.Token
                    }
                };

                var chargeService = new StripeChargeService("your private key here");
                var stripeCharge = chargeService.Create(myCharge);

                return stripeCharge.Id;
           });
        }
Exemplo n.º 18
0
        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.CreditCardNumber,
                ExpirationMonth = creditCard.ExpiryDate.Month.ToString(),
                ExpirationYear = creditCard.ExpiryDate.Year.ToString(),
                Cvc = creditCard.CVC
            };

            var chargeService = new StripeChargeService(StripeApiKey);
            var response = chargeService.Create(chargeDetails);

            return response.Paid;
        }
        public void Charge(string username, SubscriptionChargeDto subscriptionChargeDto)
        {
            var chargeOptions = new StripeChargeCreateOptions()
            {
                Amount = 18000,
                Currency = "cad",
                Source = new StripeSourceOptions() {  TokenId = subscriptionChargeDto.Token },
                Description = "Membership Payment",
                ReceiptEmail = username
            };

            var chargeService = new StripeChargeService();
            var stripeCharge = chargeService.Create(chargeOptions);

            var user = uow.Users.GetAll()
                .Include(x => x.Accounts)
                .Include("Accounts.Profiles")
                .Single(x => x.Username == username);
            var account = user.Accounts.First();
            account.AccountStatus = AccountStatus.Paid;
            uow.SaveChanges();
        }
Exemplo n.º 20
0
        public static string ChargeCustomer(paymentrequestforcharge objchargereq)
        {
            var myCharge = new StripeChargeCreateOptions();
            // always set these properties
            myCharge.Amount = ConvertToCents(objchargereq.amount);
            myCharge.Currency = "usd";

            // set this if you want to
            myCharge.Description = objchargereq.description;

            // setting up the card
            // setting up the card
            myCharge.Source = new StripeSourceOptions
            {
                TokenId = objchargereq.tokenid
            };

            var chargeService = new StripeChargeService();
            StripeCharge stripeCharge = chargeService.Create(myCharge);

            return stripeCharge.Id;
        }
        public bool Charge(PaymentInfo payment, out string errorString, out string transactionId)
        {
            // Create the customer
            // Create the charge
            var service = new StripeChargeService();
            var charge = service.Create(new StripeChargeCreateOptions
            {
                Amount = (int)(payment.ChargeAmount * 100),
                Currency = "USD",
                Description = payment.Description,
                Source = new StripeSourceOptions
                {
                    Name = payment.NameOnCard,
                    Number = payment.CardNumber,
                    Cvc = payment.CVV,
                    ExpirationYear = payment.ExpirationYear.ToString(),
                    ExpirationMonth = payment.ExpirationMonth.ToString().PadLeft(2, '0'),
                    AddressLine1 = payment.AddressLine1,
                    AddressLine2 = payment.AddressLine2,
                    AddressCity = payment.City,
                    AddressState = payment.State,
                    AddressZip = payment.PostCodeOrZip
                }
            });

            if (!charge.Paid)
            {
                transactionId = null;
                errorString = charge.FailureMessage ?? "Unable to process this transaction at this time.";
                return false;
            }
            else
            {
                transactionId = charge.Id;
                errorString = null;
                return true;
            }
        }
        public async Task<string> ProcessPayment(IStripeTransaction transaction, string currency, string privateKey)
        {
            return await Task.Run(() =>
            {
                var myCharge = new StripeChargeCreateOptions
                {
                    Amount = (int)(transaction.Amount * 100),
                    Currency = currency,
                    Description = "",
                    Source = new StripeSourceOptions
                    {
                        TokenId = transaction.Token
                    }
                };

                var chargeService = new StripeChargeService(privateKey);
                var stripeCharge = chargeService.Create(myCharge);

                return stripeCharge.Id;

            });

        }
Exemplo n.º 23
0
        public override ApiInfo CapturePayment( Order order, IDictionary<string, string> settings )
        {
            try {
            order.MustNotBeNull( "order" );
            settings.MustNotBeNull( "settings" );
            settings.MustContainKey( "mode", "settings" );
            settings.MustContainKey( settings[ "mode" ] + "_secret_key", "settings" );

            StripeChargeService chargeService = new StripeChargeService( settings[ settings[ "mode" ] + "_secret_key" ] );
            StripeCharge charge = chargeService.Capture( order.TransactionInformation.TransactionId, (int)order.TransactionInformation.AmountAuthorized.Value * 100 );

            return new ApiInfo( charge.Id, GetPaymentState( charge ) );
              } catch ( Exception exp ) {
            LoggingService.Instance.Log( exp, "Stripe(" + order.OrderNumber + ") - GetStatus" );
              }

              return null;
        }
Exemplo n.º 24
0
        public async Task<ActionResult> OrderAction(int id, int status)
        {
            var order = await _orderService.FindAsync(id);

            if (order == null)
                return new HttpNotFoundResult();

            // Get the latest successful transaction
            var transactionQuery = await _orderTransactionService.Query(x => x.OrderID == id && string.IsNullOrEmpty(x.FailureCode)).SelectAsync();
            var transaction = transactionQuery.OrderByDescending(x => x.Created).FirstOrDefault();

            if (transaction == null)
            {
                var resultFailure = new { Success = "false", Message = "Transaction not found" };
                return Json(resultFailure, JsonRequestBehavior.AllowGet);
            }

            if (status == (int)Enum_OrderStatus.Cancelled)
            {
                // Update order
                order.Modified = DateTime.Now;
                order.Status = status;
                order.ObjectState = Repository.Pattern.Infrastructure.ObjectState.Modified;
                _orderService.Update(order);

            }
            else if (status == (int)Enum_OrderStatus.Confirmed)
            {
                // Update order
                order.Modified = DateTime.Now;
                order.Status = status;
                order.ObjectState = Repository.Pattern.Infrastructure.ObjectState.Modified;
                _orderService.Update(order);

                // Update Transaction
                transaction.IsCaptured = true;
                transaction.LastUpdated = DateTime.Now;
                _orderTransactionService.Update(transaction);

                // Capture payment
                var chargeService = new StripeChargeService(CacheHelper.GetSettingDictionary(Enum_SettingKey.StripeApiKey).Value);
                StripeCharge stripeCharge = chargeService.Capture(transaction.ChargeID);
            }

            await _unitOfWorkAsync.SaveChangesAsync();

            var result = new { Success = "true", Message = "" };
            return Json(result, JsonRequestBehavior.AllowGet);
        }
Exemplo n.º 25
0
        public override CallbackInfo ProcessCallback( Order order, HttpRequest request, IDictionary<string, string> settings )
        {
            CallbackInfo callbackInfo = null;

              try {
            order.MustNotBeNull( "order" );
            request.MustNotBeNull( "request" );
            settings.MustNotBeNull( "settings" );
            settings.MustContainKey( "mode", "settings" );
            settings.MustContainKey( settings[ "mode" ] + "_secret_key", "settings" );

            // If in test mode, write out the form data to a text file
            if ( settings.ContainsKey( "mode" ) && settings[ "mode" ] == "test" ) {
              LogRequest( request, logPostData: true );
            }

            StripeChargeCreateOptions chargeOptions = new StripeChargeCreateOptions {
              AmountInCents = (int)( order.TotalPrice.Value.WithVat * 100 ),
              Currency = CurrencyService.Instance.Get( order.StoreId, order.CurrencyId ).IsoCode,
              TokenId = request.Form[ "stripeToken" ],
              Description = order.CartNumber,
              Capture = settings.ContainsKey( "capture" ) && ( settings[ "capture" ].TryParse<bool>() ?? false )
            };

            StripeChargeService chargeService = new StripeChargeService( settings[ settings[ "mode" ] + "_secret_key" ] );
            StripeCharge charge = chargeService.Create( chargeOptions );

            if ( charge.AmountInCents != null && charge.Paid != null && charge.Paid.Value ) {
              callbackInfo = new CallbackInfo( (decimal)charge.AmountInCents.Value / 100, charge.Id, charge.Captured != null && charge.Captured.Value ? PaymentState.Captured : PaymentState.Authorized );

            }

              } catch ( StripeException e ) {
            // Pass through request fields
            string requestFields = string.Join( "", request.Form.AllKeys.Select( k => "<input type=\"hidden\" name=\"" + k + "\" value=\"" + request.Form[ k ] + "\" />" ) );

            //Add error details from the exception.
            requestFields = requestFields + "<input type=\"hidden\" name=\"TransactionFailed\" value=\"true\" />";
            requestFields = requestFields + "<input type=\"hidden\" name=\"FailureReason.chargeId\" value=\"" + e.StripeError.ChargeId + "\" />";
            requestFields = requestFields + "<input type=\"hidden\" name=\"FailureReason.Code\" value=\"" + e.StripeError.Code + "\" />";
            requestFields = requestFields + "<input type=\"hidden\" name=\"FailureReason.Error\" value=\"" + e.StripeError.Error + "\" />";
            requestFields = requestFields + "<input type=\"hidden\" name=\"FailureReason.ErrorSubscription\" value=\"" + e.StripeError.ErrorSubscription + "\" />";
            requestFields = requestFields + "<input type=\"hidden\" name=\"FailureReason.ErrorType\" value=\"" + e.StripeError.ErrorType + "\" />";
            requestFields = requestFields + "<input type=\"hidden\" name=\"FailureReason.Message\" value=\"" + e.StripeError.Message + "\" />";
            requestFields = requestFields + "<input type=\"hidden\" name=\"FailureReason.Parameter\" value=\"" + e.StripeError.Parameter + "\" />";

            string paymentForm = PaymentMethodService.Instance.Get( order.StoreId, order.PaymentInformation.PaymentMethodId.Value ).GeneratePaymentForm( order, requestFields );

            //Force the form to auto submit
            paymentForm += "<script type=\"text/javascript\">document.forms[0].submit();</script>";

            //Write out the form
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Write( paymentForm );
            HttpContext.Current.Response.End();
              } catch ( Exception exp ) {
            LoggingService.Instance.Log( exp, "Stripe(" + order.CartNumber + ") - ProcessCallback" );
              }

              return callbackInfo;
        }
Exemplo n.º 26
0
        public ActionResult Payment(int orderId, OrderPaymentModel model)
        {
            if (ModelState.IsValid)
            {
                Order order = OrderService.GetOrder(orderId);

                AppendOrderDetails(model, ref order);

                var chargeService = new StripeChargeService();

                StripeCharge stripeCharge = chargeService.Create(
                    new StripeChargeCreateOptions
                    {
                        AmountInCents = (int)(order.Total * 100), // in cents
                        Currency = "usd",
                        TokenId = order.StripeToken
                    });

                if (stripeCharge.Paid.HasValue && stripeCharge.Paid.Value)
                {
                    string confirmationCode = OrderService.GenerateConfirmation();

                    order.ConfirmationCode = confirmationCode;
                    order = OrderService.Scrub(order);
                    order = OrderService.CompleteOrder(order);

                    Utilities.SendOrderEmail(order);
                    Utilities.SendConfirmationEmail(order);

                    return RedirectToAction("Confirmation", new { orderId = order.OrderId, confirmation = order.ConfirmationCode });
                }
                else
                {
                    order.OrderState = Constants.OrderState.ERROR;
                    order.Message = "Card processing error. Please try again.";
                    OrderService.SaveOrder(order);
                }
            }

            return View(model);
        }
        public bool OrderAction(int id, int status, out string message)
        {
            message = string.Empty;

            var order = _orderService.Find(id);

            // Get the latest successful transaction
            var transactionQuery = _transactionService.Query(x => x.OrderID == id && string.IsNullOrEmpty(x.FailureCode)).Select();
            var transaction = transactionQuery.OrderByDescending(x => x.Created).FirstOrDefault();

            if (transaction == null)
            {
                message = "[[[Transaction not found]]]";
                return false;
            }

            if (status == (int)Enum_OrderStatus.Cancelled)
            {
                // Update order
                order.Modified = DateTime.Now;
                order.Status = status;
                order.ObjectState = Repository.Pattern.Infrastructure.ObjectState.Modified;
                _orderService.Update(order);

            }
            else if (status == (int)Enum_OrderStatus.Confirmed)
            {
                // Update order
                order.Modified = DateTime.Now;
                order.Status = status;
                order.ObjectState = Repository.Pattern.Infrastructure.ObjectState.Modified;
                _orderService.Update(order);

                // Update Transaction
                transaction.IsCaptured = true;
                transaction.LastUpdated = DateTime.Now;
                _transactionService.Update(transaction);

                // Capture payment
                var chargeService = new StripeChargeService(CacheHelper.GetSettingDictionary(StripePlugin.SettingStripeApiKey).Value);
                StripeCharge stripeCharge = chargeService.Capture(transaction.ChargeID);
            }

            _unitOfWorkAsync.SaveChanges();
            _unitOfWorkAsyncStripe.SaveChanges();

            return true;
        }
        public async Task<ActionResult> Payment(int id, string stripeToken, string stripeEmail)
        {
            var selectQuery = await _orderService.Query(x => x.ID == id).Include(x => x.Listing).SelectAsync();

            // Check if order exists
            var order = selectQuery.FirstOrDefault();
            if (order == null)
                return new HttpNotFoundResult();

            var stripeConnectQuery = await _stripConnectService.Query(x => x.UserID == order.UserProvider).SelectAsync();
            var stripeConnect = stripeConnectQuery.FirstOrDefault();

            if (stripeConnect == null)
                return new HttpNotFoundResult();

            //https://stripe.com/docs/checkout
            var charge = new StripeChargeCreateOptions();

            // always set these properties
            charge.Amount = order.PriceInCents;
            charge.Currency = CacheHelper.Settings.Currency;
            charge.Source = new StripeSourceOptions()
            {
                TokenId = stripeToken
            };

            // set booking fee
            var bookingFee = (int)Math.Round(CacheHelper.Settings.TransactionFeePercent * order.PriceInCents);
            if (bookingFee < CacheHelper.Settings.TransactionMinimumFee * 100)
                bookingFee = (int)(CacheHelper.Settings.TransactionMinimumFee * 100);

            charge.ApplicationFee = bookingFee;
            charge.Capture = false;
            charge.Description = order.Description;
            charge.Destination = stripeConnect.stripe_user_id;
            var chargeService = new StripeChargeService(CacheHelper.GetSettingDictionary("StripeApiKey").Value);
            StripeCharge stripeCharge = chargeService.Create(charge);

            // Update order status
            order.Status = (int)Enum_OrderStatus.Pending;
            order.PaymentPlugin = StripePlugin.PluginName;
            _orderService.Update(order);

            // Save transaction
            var transaction = new StripeTransaction()
            {
                OrderID = id,
                ChargeID = stripeCharge.Id,
                StripeEmail = stripeEmail,
                StripeToken = stripeToken,
                Created = DateTime.Now,
                LastUpdated = DateTime.Now,
                FailureCode = stripeCharge.FailureCode,
                FailureMessage = stripeCharge.FailureMessage,
                ObjectState = Repository.Pattern.Infrastructure.ObjectState.Added
            };

            _transactionService.Insert(transaction);

            await _unitOfWorkAsync.SaveChangesAsync();
            await _unitOfWorkAsyncStripe.SaveChangesAsync();

            ClearCache();

            // Payment succeeded
            if (string.IsNullOrEmpty(stripeCharge.FailureCode))
            {
                // Send message to the user
                var message = new MessageSendModel()
                {
                    UserFrom = order.UserReceiver,
                    UserTo = order.UserProvider,
                    Subject = order.Listing.Title,
                    ListingID = order.ListingID,
                    Body = HttpContext.ParseAndTranslate(string.Format(
                    "[[[Order Requested - %0 - Total Price %1 %2|||{0}|||{1}|||{2}]]]",
                    order.Description,
                    order.Price,
                    order.Currency))
                };

                await MessageHelper.SendMessage(message);

                TempData[TempDataKeys.UserMessage] = "[[[Thanks for your order! You payment will not be charged until the provider accepted your request.]]]";
                return RedirectToAction("Orders", "Payment");
            }
            else
            {
                TempData[TempDataKeys.UserMessageAlertState] = "bg-danger";
                TempData[TempDataKeys.UserMessage] = stripeCharge.FailureMessage;

                return RedirectToAction("Payment");
            }
        }
Exemplo n.º 29
0
        public ActionResult Payment(Member member, string stripeToken)
        {
            string token = stripeToken;

            int feeAmount;
            string feeOption;
            string paymentMethod;

            switch(member.FeeOption)
            {
                case FeeOption.OneYearMembership:
                    feeAmount = 10;
                    feeOption = "one year membership with us";
                    break;
                case FeeOption.FiveYearMembership:
                    feeAmount = 40;
                    feeOption = "five year membership with us";
                    break;
                case FeeOption.LifetimeMembership:
                    feeAmount = 200;
                    feeOption = "lifetime membership with us";
                    break;
                default:
                    feeAmount = 500;
                    feeOption = "one year patronage fee";
                    break;
            }

            switch (member.PaymentMethod)
            {
                case PaymentMethod.Cash:
                    paymentMethod = "cash";
                    break;
                case PaymentMethod.Cheque:
                    paymentMethod = "cheque";
                    break;
                default:
                    paymentMethod = "credit card";
                    break;
            }

            var myCharge = new StripeChargeCreateOptions();
            myCharge.Amount = feeAmount * 100;
            myCharge.Currency = "cad";
            myCharge.Description = "Membership/Patronage Fee Payment";
            myCharge.Source = new StripeSourceOptions()
            {
                TokenId = token
            };

            var chargeService = new StripeChargeService();
            try
            {
                StripeCharge stripeCharge = chargeService.Create(myCharge);
            }
            catch (StripeException e)
            {
                if (e.StripeError.ErrorType == "card_error" || e.StripeError.ErrorType == "invalid_request_error")
                {
                    ViewBag.Error = e.StripeError.Message;
                }
                else
                {
                    ViewBag.Error = "Something went wrong on our side and we couldn't process your donation. We hope you don't mind trying to submit your donation again!";
                }

                ViewBag.FeeAmount = feeAmount;
                ViewBag.FeeOption = feeOption;

                return View(member);
            }

            try
            {
                AWICEmailHelper.SendFeePaidEmail(member, feeAmount, feeOption);
                AWICEmailHelper.SendMemberRegistrationReceivedEmail(member, feeAmount, feeOption, paymentMethod);
            }
            catch(Exception e)
            {
                // Ignore, since email not sent to member or AWIC is not an issue
            }

            ViewBag.FeeAmount = feeAmount;
            ViewBag.FeeOption = feeOption;
            ViewBag.PaymentMethod = paymentMethod;

            return View("SignUpComplete", member);
        }
Exemplo n.º 30
0
        public override ApiInfo RefundPayment( Order order, IDictionary<string, string> settings )
        {
            try {
            order.MustNotBeNull( "order" );
            settings.MustNotBeNull( "settings" );
            settings.MustContainKey( "mode", "settings" );
            settings.MustContainKey( settings[ "mode" ] + "_secret_key", "settings" );

            StripeChargeService chargeService = new StripeChargeService( settings[ settings[ "mode" ] + "_secret_key" ] );
            StripeCharge charge = chargeService.Refund( order.TransactionInformation.TransactionId );

            return new ApiInfo( charge.Id, GetPaymentState( charge ) );
              } catch ( Exception exp ) {
            LoggingService.Instance.Error<Stripe>( "Stripe(" + order.OrderNumber + ") - RefundPayment", exp );
              }

              return null;
        }