Esempio n. 1
0
        public void SendRefundEmail(StripeCharge stripeCharge)
        {
            var message = new MailMessage() { IsBodyHtml = true };
            message.To.Add(new MailAddress("*****@*****.**"));
            message.Subject = string.Format("refund requested on charge: {0}", stripeCharge.Id);
            message.Body = string.Format("<p>{0}</p>", string.Format("A customer at this email address {0} was issued a refund on their purchase: '{1}'.  Please follow up to determine a reason.", stripeCharge.ReceiptEmail, stripeCharge.Description));

            using (var smtp = new SmtpClient())
            {
                smtp.Send(message);
            }
        }
Esempio n. 2
0
        public void SendPaymentReceivedFromInvoicePaymentSucceed(StripeCharge stripeCharge)
        {
            var customer = stripeCharge.Customer;
            var message = new MailMessage() { IsBodyHtml = true };
            message.To.Add(new MailAddress("*****@*****.**"));
            message.Subject = string.Format("Receipt for purchasing  {0} - {1}", stripeCharge.Description, stripeCharge.Id);
            message.Body = string.Format("<p>{0}</p>", string.Format("A customer at this email address {0} confirmation of this purchase: '{1}'.  Please follow up to determine a reason.", stripeCharge.ReceiptEmail, stripeCharge.Description));

            using (var smtp = new SmtpClient())
            {
                smtp.Send(message);
            }
        }
Esempio n. 3
0
        protected PaymentState GetPaymentState( StripeCharge charge )
        {
            PaymentState paymentState = PaymentState.Initialized;

              if ( charge.Paid != null && charge.Paid.Value ) {
            paymentState = PaymentState.Authorized;

            if ( charge.Captured != null && charge.Captured.Value ) {
              paymentState = PaymentState.Captured;

              if ( charge.Refunded != null && charge.Refunded.Value ) {
            paymentState = PaymentState.Refunded;
              }
            } else {
              if ( charge.Refunded != null && charge.Refunded.Value ) {
            paymentState = PaymentState.Cancelled;
              }
            }
              }

              return paymentState;
        }
        public void Complete(StripeCharge charge)
        {
            if (this.State != States.Initiated)
            {
                throw new InvalidOperationException();
            }

            this.StripeData = JsonConvert.SerializeObject(charge);

            this.State = States.Completed;
            this.AddEvent(new PaymentCompleted { SourceId = this.Id, PaymentSourceId = this.PaymentSourceId });
        }
Esempio n. 5
0
        void IEmailHelper.SendCustomerChargeFailed(StripeCharge charge, string customerName, string customerEmail, string last4)
        {
            Guard.ArgumentNotNullOrEmptyString(customerName, "customerName");
            Guard.ArgumentNotNullOrEmptyString(customerEmail, "customerEmail");
            Guard.ArgumentNotNullOrEmptyString(last4, "last4");
            Guard.ArgumentNotNull(() => charge);

            Dictionary<string, string> values = new Dictionary<string, string>();
            decimal amount = Decimal.Divide((Decimal)charge.AmountInCents, 100);
            values.Add("Last4", last4);
            values.Add("FirstName", customerName);
            values.Add("InvoiceDate", charge.Created.ToString());
            values.Add("FailureMessage", charge.FailureMessage);
            values.Add("Amount", amount.ToString("C"));

            var send = this as IEmailHelper;
            string fileName = String.Empty;

            if (root.Contains("~"))
            {
                fileName = System.Web.HttpContext.Current.Server.MapPath(root + "ChargeFailed.txt");
            }
            else
            {
                fileName = root + "ChargeFailed.txt";
            }

            send.SetupEmail(values, customerEmail, fileName, "We Need You Have Credit Card Charge Notice.");
        }
Esempio n. 6
0
        public void ChargeCustomer_ValidParameters_Successful()
        {
            //Arrange
            StripeCharge charge = new StripeCharge();
            charge.Id = chargeId;

            Mock<StripeChargeService> custChargeService = new Mock<StripeChargeService>(null);
            custChargeService.Setup(charg => charg.Create(It.IsAny<StripeChargeCreateOptions>(), null))
                .Returns(charge);
            stripeAccessor = new StripeAccessorService(subService.Object, custChargeService.Object, cusService.Object);

            //Act
            String returnedId = stripeAccessor.ChargeCustomer(customerId, 2, 15, 2016, 1, 25);

            //Assert
            Assert.That(returnedId, Is.EqualTo(chargeId));
        }
Esempio n. 7
0
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (Session["PKG"] != null)
            {
                try
                {
                    var package = (Package)Session["PKG"];

                    using (var dataContext = new nChangerDb())
                    {
                        var user = dataContext.Users.Find(UserId);
                        if (user != null)
                        {
                            #region Charge....

                            var myCharge = new StripeChargeCreateOptions
                            {
                                Amount = (int)(package.Price * 100),
                                Currency = "usd",
                                Description = "Subscription Charges for " + package.PackageName + " package for " + UserName,
                                Source = new StripeSourceOptions()
                                {
                                    // set these properties if passing full card details (do not
                                    // set these properties if you set TokenId)
                                    Object = "card",
                                    Number = txtCardNumber.Text,
                                    ExpirationYear = txtExpieryYear.Text,
                                    ExpirationMonth = ddlExpiryMonth.SelectedValue,
                                    AddressCountry = user.Country, // optional
                                    AddressLine1 = user.Address, // optional
                                    AddressLine2 = user.Address2, // optional
                                    AddressCity = user.City, // optional
                                    AddressState = user.State, // optional
                                    AddressZip = user.Zip, // optional
                                    Name = UserName, // optional
                                    Cvc = txtCVC.Text, // optional
                                    ReceiptEmail = user.Email
                                },

                                Capture = true
                            };

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

                                #region Log Entry... 

                                dataContext.UserPayments.Add(new UserPayment
                                {
                                    Id = Guid.NewGuid(),
                                    Amount = (decimal)(stripeCharge.Amount / 100),
                                    Currency = stripeCharge.Currency,
                                    Status = stripeCharge.Status,
                                    FailureCode = stripeCharge.FailureCode,
                                    FailureMessage = stripeCharge.FailureMessage,
                                    PackageId = package.Id,
                                    PaymentDate = stripeCharge.Created,
                                    UserId = UserId,
                                    EntryIP = CommonFunctions.GetIpAddress(),
                                    EntryId = UserId,
                                });


                                if (stripeCharge.Status.ToLower().Equals("succeeded"))
                                    dataContext.Database.ExecuteSqlCommand("UPDATE Users SET IsPaidMember='1' WHERE UserId='" +
                                                                           UserId + "'");
                                 
                                #endregion Log Entry...
                            }
                            catch(Exception error)
                            {
                                dataContext.UserPayments.Add(new UserPayment
                                {
                                    Id = Guid.NewGuid(),
                                    Amount = (decimal)package.Price,
                                    Currency = "usd",
                                    Status = "Failed",
                                    FailureCode = stripeCharge.FailureCode,
                                    FailureMessage = error.Message,
                                    PackageId = package.Id,
                                    PaymentDate = DateTime.Now,
                                    UserId = UserId,
                                    EntryIP = CommonFunctions.GetIpAddress(),
                                    EntryId = UserId,
                                });
                            }

                            #endregion Charge....

                            dataContext.SaveChanges();

                            #region Response...

                            Session.Add("PMS", stripeCharge);

                            Response.Redirect("PaymentResponse.aspx");

                            #endregion Response...

                        }
                    }
                }
                catch (Exception exception)
                {
                    
                }
               
            }

        }
Esempio n. 8
0
        public ActionResult Payment(string stripeToken, int?amount, string Name, string Email, string Phone, int?tripId, string userName, string donationMsg)
        {
            if (tripId == null)
            {
                return(HttpNotFound());
            }

            ViewBag.TripId  = tripId;
            ViewBag.Message = null;
            if (!string.IsNullOrEmpty(stripeToken))
            {
                var attachDonor = new Donor();

                //Check for an existing donor
                var existingDonor = db.Donors.Where(d => d.Email == Email).FirstOrDefault();

                //Add donor record if none existing
                if (existingDonor == null)
                {
                    string name = (Name == "" ? "Anonymous" : Name);

                    Donor donorInfo = new Donor
                    {
                        Name  = name,
                        Email = Email,
                        Phone = Phone
                    };

                    db.Donors.Add(donorInfo);
                    db.SaveChanges();

                    attachDonor = donorInfo;
                }
                else
                {
                    attachDonor = existingDonor;
                }

                if (ModelState.IsValid)
                {
                    Trip tripInfo = db.Trips.SingleOrDefault(t => t.Id == tripId);
                    //Create the charge request to send to stripe
                    var chargeRequest = new StripeChargeCreateOptions()
                    {
                        Amount   = amount,
                        Currency = "USD",
                        SourceTokenOrExistingSourceId = stripeToken,
                        Description = $"Destination:{tripInfo.Destination} || Student Name:{ tripInfo.Student.FirstName},{ tripInfo.Student.LastName}",
                    };
                    var service = new StripeChargeService(WebConfigurationManager.AppSettings["PrivateKey"]);
                    try
                    {
                        result = service.Create(chargeRequest);

                        if (result.Paid)
                        {
                            if (string.IsNullOrEmpty(donationMsg))
                            {
                                donationMsg = "No Message";
                            }
                            //Create a donation in Db
                            var donation = new Donation
                            {
                                Amount      = amount / 100,
                                HaveThanked = false,
                                TripId      = (int)tripId,
                                Donor       = attachDonor,
                                Created     = DateTime.Now,
                                DonationMsg = donationMsg,
                            };
                            db.Donations.Add(donation);
                            db.SaveChanges();

                            ViewBag.Message = "Payment Successful";

                            if (tripId != null)
                            {
                                //Update Percentage for trip
                                Trip trip    = db.Trips.Find(tripId);
                                var  donated = db.Donations
                                               .Where(d => d.TripId == trip.Id)
                                               .Sum(d => d.Amount);
                                double target     = trip.TargetAmnt;
                                double rawPercent = (double)((donated / target) * 100);
                                trip.PercentOfAmnt   = Math.Round(rawPercent, 2);
                                db.Entry(trip).State = System.Data.Entity.EntityState.Modified;
                                db.SaveChanges();
                            }

                            //Send Receipt
                            //var transportWeb = new SendGrid.Web("SENDGRID_APIKEY");
                            //transportWeb.DeliverAsync(myMessage);
                            SendReceiptEmail(Email, amount, Name, tripId);
                        }
                        else
                        {
                            ViewBag.Message = result.FailureMessage;
                        }
                    }
                    catch (StripeException ex)
                    {
                        ViewBag.Message = ex.Message;
                    }
                }
            }
            string paymentMessage = ViewBag.Message;

            return(RedirectToAction(userName, new RouteValueDictionary(
                                        new { controller = "send", action = userName, paymentMsg = paymentMessage, email = Email })));
        }
Esempio n. 9
0
        public override PaymentResponse MakePayment()
        {
            try
            {
                #region Create Token
                //Get Stripe API Key
                StripeConfiguration.SetApiKey(
                    CompanyConfigurationSettings.CompanyConfigList.Find
                    (cc => cc.Name.Equals(System.Configuration.ConfigurationSettings.AppSettings["creditsHero_Stripe:ApiKey"])).Value);

                var newToken = new StripeTokenCreateOptions();

                newToken.Card = new StripeCreditCardOptions()
                {
                    Number = this.CardNumber,
                    ExpirationYear = this.ExpirationYear,
                    ExpirationMonth = this.ExpirationMonth,
                    AddressCountry = "US",
                    AddressLine1 = this.AddressLine1,
                    AddressLine2 = this.AddressLine2,
                    AddressCity = this.AddressCity,
                    AddressState = this.AddressState,
                    AddressZip = this.AddressZip,
                    Name = this.Name,
                    Cvc = this.Cvc
                };

                var tokenService = new StripeTokenService();
                StripeToken stripeToken = tokenService.Create(newToken);
                #endregion

                #region Create Charge
                var newCharge = new StripeChargeCreateOptions();
                newCharge.Amount = Int32.Parse(this.Amount.ToString());
                newCharge.Currency = "usd";
                newCharge.Description = "";
                newCharge.Capture = true;
                
                var chargeService = new StripeChargeService();

                StripeCharge stripeCharge = new StripeCharge();
                stripeCharge.LiveMode = Boolean.Parse(System.Configuration.ConfigurationSettings.AppSettings["creditsHero_Stripe:IsLive"]);
                var results = chargeService.Create(newCharge);
                #endregion

                return new PaymentResponse()
                {
                    AuthCode = results.Status,
                    Message = results.Status,
                    MessageCode = results.Status,
                    ResponseCode = results.Status,
                    TransactionId = results.Status,
                    TransactionResult = results.Status
                };
            }
            catch (System.Exception exc)
            {
                return new PaymentResponse()
                {
                    ErrorMessage = exc.Message,
                    Message = exc.StackTrace,
                    TransactionResult = String.Format("Paypal Error:{0}--{1}", exc.Message, exc.StackTrace)
                };
            }
        }