Esempio n. 1
0
        static void Main(string[] args)
        {
            //step 1 - create the request
            var request = new AuthorizationRequest("4111111111111111", "1216", 10.00M, "Test Transaction");

            //These are optional calls to the API
            //request.AddCardCode("321");

            //Customer info - this is used for Fraud Detection
            //request.AddCustomer("id", "first", "last", "address", "state", "zip");

            //order number
            //request.AddInvoice("invoiceNumber");

            //Custom values that will be returned with the response
            //request.AddMerchantValue("merchantValue", "value");

            //Shipping Address
            //request.AddShipping("id", "first", "last", "address", "state", "zip");

            //step 2 - create the gateway, sending in your credentials and setting the Mode to Test (boolean flag)
            //which is true by default
            //this login and key are the shared dev account - you should get your own if you
            //want to do more testing
            var gate = new Gateway("API-LOGIN", "TRANSACTION-KEY",true);

            //step 3 - make some money
            var response = gate.Send(request);

            Console.WriteLine("{0}: {1}",response.ResponseCode, response.Message);
            Console.Read();
        }
Esempio n. 2
0
        public void SendTest_AuthCap_Approved_CustomerIP()
        {
            //check login / password
            string sError = CheckLoginPassword();
            Assert.IsTrue(sError == "", sError);

            string responseString = "1|1|1|This transaction has been approved.|7339F5|Y|2207176015||testing|20.10|CC|auth_capture||||||||||||||||||||||||||7639D026F54F4DF70EA3F7DE5A350929||2|||||||||||XXXX1111|Visa||||||||||||||||";
            LocalRequestObject.ResponseString = responseString;
            IGatewayResponse expected = new GatewayResponse(responseString.Split('|'));

            Gateway target = new Gateway(ApiLogin, TransactionKey, true);

            IGatewayRequest request = new AuthorizationRequest("4111111111111111", "0224", (decimal)20.10, "AuthCap transaction approved testing", true);
            string description = "AuthCap transaction approved testing";
            request.CustId = "CID1234";
            request.CustomerIp = "CIP456789";
            IGatewayResponse actual = target.Send(request, description);

            Assert.AreEqual(expected.Amount, actual.Amount);
            Assert.AreEqual(expected.Approved, actual.Approved);
            Assert.AreEqual(expected.CardNumber, actual.CardNumber);
            Assert.AreEqual(expected.Message, actual.Message);
            Assert.AreEqual(expected.ResponseCode, actual.ResponseCode);

            Assert.IsTrue(actual.AuthorizationCode.Trim().Length > 0);
            Assert.IsTrue(actual.TransactionID.Trim().Length > 0);
            Assert.IsTrue(long.Parse(actual.TransactionID) > 0);
        }
		public PaymentResult Pay(CreditCardInfo info, int orderId)
		{
			Func<IGateway> openGateway = () => new Gateway(_authorizeSettings.AuthorizationApiLogin, _authorizeSettings.AuthorizationTransactionKey, _authorizeSettings.IsAuthorizationTestMode);
			var gateway = openGateway();
			var apiRequest = new AuthorizationRequest(info.CreditCardNumber, info.ExpirationDate.ToString(ExpirationDateFormat), info.Amount, "Direct Valuation Solutions, Inc.");

			apiRequest.FirstName = info.FirstName;
			apiRequest.LastName = info.LastName;
			apiRequest.Address = info.StreetAddress;
			apiRequest.City = info.City;
			apiRequest.State = info.State;
			apiRequest.Zip = info.ZIP;
			apiRequest.CardCode = info.CVVCSCCode;

			Logger.WriteInfo(String.Format("Payment started. OrderId [{0}], UserId [{1}]", orderId, _securityContext.CurrentUser.Id));

			var response = gateway.Send(apiRequest);

			Logger.WriteInfo(String.Format("Payment completed. OrderId [{0}], UserId [{1}], amount [{2}], transactionId [{3}], ResponseCode [{4}], Approved [{5}]",
				orderId, _securityContext.CurrentUser.Id, response.Amount, response.TransactionID, response.ResponseCode, response.Approved));

			const int defaultResponseCode = 1;
			var responseCode = SafeConvert.ToInt(response.ResponseCode, defaultResponseCode);
			const int responseReasonIndex = 2;
			const int defaultResponseReasonCode = 1;
			var responseReasonCode = SafeConvert.ToInt(((ResponseBase)response).RawResponse[responseReasonIndex], defaultResponseReasonCode);

			return new PaymentResult
			{
				Message = _referenceManagement.GetAuthorizeDotNetResponseMessage(responseCode, responseReasonCode),
				IsApproved = response.Approved,
				TransactionId = response.TransactionID
			};
		}
        /// <summary>
        /// This helper method will read the form post and load the values into the request, if present. This method
        /// should be used with the form builder, and expects
        /// </summary>
        public static IGatewayRequest BuildAuthAndCaptureFromPost(NameValueCollection post)
        {
            //validate the request first
            var request = new AuthorizationRequest(post);

            SerializeForm (request, post);
            return request;
        }
        public ActionResult CreditCardTest()
        {
            //What sends our transaction request
            Gateway target = new Gateway("7es9Ud9Zj2TH", "93LxQ9m54wUh26Y7", true);
            //Creating an authorization request

            IGatewayRequest request = new AuthorizationRequest("5424000000000015", "0224", (decimal)20.10, "AuthCap transaction approved testing", true);
            string description = "AuthCap transaction approved testing";
            IGatewayResponse response = target.Send(request, description);
            request.Address = "123 Main St. Denver CO 80203";

            return Content("OK");
        }
Esempio n. 6
0
        //-------------------------------------------------------------------------------------------
        public IGatewayResponse Bill(WeavverEntityContainer data, Sales_Orders order, Logistics_Addresses primaryAddress, Logistics_Addresses billingAddress)
        {
            string memo = "WEB PURCHASE";
               // Add the credit to the ledger.
               Accounting_LedgerItems item = new Accounting_LedgerItems();
               item.Id = Guid.NewGuid();
               item.OrganizationId = OrganizationId;
               if (order.Orderee.HasValue)
                    item.AccountId = order.Orderee.Value;
               else
                    item.AccountId = order.Id;
               item.LedgerType = LedgerType.Receivable.ToString();
               item.TransactionId = order.Id;
               item.PostAt = DateTime.UtcNow;
               item.Code = CodeType.Payment.ToString();
               item.Memo = "Payment from Card " + Number.Substring(Number.Length - 4);
               item.Amount = Math.Abs(order.Total.Value);

            //               order.BillingContactEmail

               // Submit to Authorize.Net
               var request = new AuthorizationRequest(Number, ExpirationMonth.ToString("D2") + ExpirationYear.ToString("D2"), order.Total.Value, memo, true);
               request.AddCustomer("", order.PrimaryContactNameFirst, order.PrimaryContactNameLast, primaryAddress.Line1, primaryAddress.State, primaryAddress.ZipCode);
               request.AddMerchantValue("OrderId", order.Id.ToString());
               request.AddMerchantValue("CreatedBy", order.CreatedBy.ToString());
               request.AddMerchantValue("LedgerItemId", item.Id.ToString());
               request.AddShipping("", order.BillingContactNameFirst, order.BillingContactNameLast, billingAddress.Line1, billingAddress.State, billingAddress.ZipCode);
               var gate = new Gateway(ConfigurationManager.AppSettings["authorize.net_loginid"], ConfigurationManager.AppSettings["authorize.net_transactionkey"], (ConfigurationManager.AppSettings["authorize.net_testmode"] == "true"));

               var response = gate.Send(request, memo);
               item.ExternalId = response.TransactionID;
               if (!response.Approved)
               {
                    //item.Voided = true;
                    //item.VoidedBy = Guid.Empty;
                    item.Memo += "\r\nPayment failed: Code " + response.ResponseCode + ", " + response.Message;
               }
               data.Accounting_LedgerItems.Add(item);
               return response;
        }
Esempio n. 7
0
        public ActionResult Make(PaymentInputModel inputModel)
        {
            var job = (Job)Session["Job"];

            // todo wrap - up in service
            var request = new AuthorizationRequest(inputModel.CardNumber.ToString(), inputModel.ExpiryDate, job.Quote.Total, job.Reference);

            var gate = new Gateway(paymentSettings.GetApiLogin(), paymentSettings.GetTransactionKey());

            var response = gate.Send(request);

            if (response.Approved)
            {
                jobService.MakePayment(job, response.Amount, response.TransactionID);
                jobService.SaveJob(job);

                Session["Job"] = job;

                var responseViewModel = new PaymentResponseViewModel
                {
                    ResponseCode = response.ResponseCode,
                    Message = response.Message,
                    TransactionId = response.TransactionID,
                    Amount = response.Amount,
                    Timestamp = job.PaymentMade.Value,
                    JobReference = job.Reference
                };

                Session["PaymentResult"] = responseViewModel;

                return RedirectToUmbracoPage(1185);
            }

            var viewModel = new PaymentViewModel
            {
                Total = job.Quote.Total
            };

            return View("Index", viewModel);
        }
Esempio n. 8
0
    private bool CreateCharge()
    {
        var apiKey = System.Configuration.ConfigurationManager.AppSettings["APIKeySmithEvents"];
        var transKey = System.Configuration.ConfigurationManager.AppSettings["TransactionKeySmithEvents"];
        var isTest = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["IsTestModeSmithEvents"]);

        var amt = Convert.ToDecimal(PaymentDropDown.SelectedValue);

        var request = new AuthorizationRequest(CreditCardNumberTextBox.Text.Trim(), MonthTextBox.Text.Trim() + YearTextBox.Text.Trim(), amt,
               "Smith Events - MIRAVAL JOURNEYS 10 DAY CROATIA & BOSNIA - WITH STAY ON HVAR- " + amt, AddressTextBox.Text.Trim(), CityTextBox.Text.Trim(), State.SelectedValue, ZipTextBox.Text.Trim(),
               CVCTextBox.Text.Trim(), FirstNameTextBox.Text, LastNameTextBox.Text);

        //step 2 - create the gateway, sending in your credentials
        var gate = new Gateway(apiKey, transKey, isTest);

        //step 3 - make some money
        var response = gate.Send(request);
        if (!response.Approved)
        {
            Util.SendMail("*****@*****.**", "*****@*****.**","Smith Events - MIRAVAL JOURNEYS 10 DAY CROATIA & BOSNIA - WITH STAY ON HVAR Credit Card Not Accepted", response.Message, false);
            throw new InvalidOperationException("Charge failed: " + response.Message);
        }
        return true;
    }
        public ActionResult Authorize() {
            HttpContext ctx = System.Web.HttpContext.Current;
            Customer customer = new Customer();
            Settings settings = ViewBag.settings;
            // Retrieve Customer from Sessions/Cookie
            customer.GetFromStorage(ctx);
            if (!customer.Cart.Validate()) {
                return RedirectToAction("Index", "Cart");
            }

            if (customer.Cart.GetPaymentID() > 0) {
                UDF.ExpireCart(ctx, customer.ID);
                return RedirectToAction("Index", "Cart");
            }

            customer.BindAddresses();

            decimal amount = customer.Cart.getTotal();
            string cardnum = Request.Form["cardnumber"];
            string month = Request.Form["expiremonth"];
            string year = Request.Form["expireyear"];
            string cvv = Request.Form["cvv"];
            string first = Request.Form["first"];
            string last = Request.Form["last"];

            //step 1 - create the request
            IGatewayRequest request = new AuthorizationRequest(cardnum, month + year, amount, "Transaction");

            //These are optional calls to the API
            request.AddCardCode(cvv);

            //Customer info - this is used for Fraud Detection
            request.AddCustomer(customer.ID.ToString(), first, last, customer.Cart.Billing.street1 + ((customer.Cart.Billing.street2 != "") ? " " + customer.Cart.Billing.street2 : ""), customer.Cart.Billing.State1.abbr, customer.Cart.Billing.postal_code);

            //order number
            //request.AddInvoice("invoiceNumber");

            //Custom values that will be returned with the response
            //request.AddMerchantValue("merchantValue", "value");

            //Shipping Address
            request.AddShipping(customer.ID.ToString(), customer.Cart.Shipping.first, customer.Cart.Shipping.last, customer.Cart.Shipping.street1 + ((customer.Cart.Shipping.street2 != "") ? " " + customer.Cart.Shipping.street2 : ""), customer.Cart.Shipping.State1.abbr, customer.Cart.Shipping.postal_code);


            //step 2 - create the gateway, sending in your credentials and setting the Mode to Test (boolean flag)
            //which is true by default
            //this login and key are the shared dev account - you should get your own if you 
            //want to do more testing
            bool testmode = false;
            if (settings.Get("AuthorizeNetTestMode").Trim() == "true") {
                testmode = true;
            }

            Gateway gate = new Gateway(settings.Get("AuthorizeNetLoginKey"), settings.Get("AuthorizeNetTransactionKey"), testmode);
            customer.Cart.SetStatus((int)OrderStatuses.PaymentPending);

            //step 3 - make some money
            IGatewayResponse response = gate.Send(request);
            if (response.Approved) {
                customer.Cart.AddPayment("credit card", response.AuthorizationCode, "Complete");
                customer.Cart.SetStatus((int)OrderStatuses.PaymentComplete);
                customer.Cart.SendConfirmation(ctx);
                customer.Cart.SendInternalOrderEmail(ctx);
                int cartid = customer.Cart.ID;
                
                Cart new_cart = new Cart().Save();
                new_cart.UpdateCart(ctx, customer.ID);
                DateTime cookexp = Request.Cookies["hdcart"].Expires;
                HttpCookie cook = new HttpCookie("hdcart", new_cart.ID.ToString());
                cook.Expires = cookexp;
                Response.Cookies.Add(cook);

                customer.Cart = new_cart;
                customer.Cart.BindAddresses();

                return RedirectToAction("Complete", new { id = cartid });
            } else {
                customer.Cart.SetStatus((int)OrderStatuses.PaymentDeclined);
                return RedirectToAction("Index", new { message = response.Message });
            }
        }
Esempio n. 10
0
        private bool CreateCharge(out int amt, int deposit)
        {
            var apiKey = String.Empty;
            var transKey = String.Empty;

            var isTest = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["IsTestMode"]);

            if (isTest)
            {
                apiKey = System.Configuration.ConfigurationManager.AppSettings["TestAPIkEY"];
                transKey = System.Configuration.ConfigurationManager.AppSettings["TestTransactionKey"];
            }
            else
            {
                apiKey = System.Configuration.ConfigurationManager.AppSettings["APIKey"];
                transKey = System.Configuration.ConfigurationManager.AppSettings["TransactionKey"];
            }

            amt = 0;

            if (deposit > 0)
            {
                amt = deposit;
            }
            else
            {
                if (ViewState["typ"].ToString().ToLower() == "grad")
                {
                    amt = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["gradCost"]);
                }
                else
                {
                    amt = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["newsletterpromoCost"]);
                }
            }

            if (deposit == 0)
            {
                amt = amt + Int32.Parse(ViewState["Subtotal"].ToString());
            }

            //step 1
            var request = new AuthorizationRequest(CreditCardNumberTextBox.Text.Trim(),
                                                   MonthTextBox.Text.Trim() + YearTextBox.Text.Trim(),
                                                   amt,
                                                   "Sacred Contracts Online Purchase - " + amt,
                                                   AddressTextBox.Text.Trim(),
                                                   CityTextBox.Text.Trim(),
                                                   State.SelectedValue,
                                                   ZipTextBox.Text.Trim(),
                                                   CVCTextBox.Text.Trim(),
                                                   FirstNameTextBox.Text,
                                                   LastNameTextBox.Text);

            //step 2 - create the gateway, sending in your credentials
            var gate = new Gateway(apiKey, transKey, isTest);

            //step 3 - make some money
            var response = gate.Send(request);

            if (!response.Approved)
            {
                string CardNumber = CreditCardNumberTextBox.Text.Trim();
                var sb = new StringBuilder();
                sb.Append("Name: ").Append(FirstNameTextBox.Text.Trim()).Append(" ").AppendLine(LastNameTextBox.Text.Trim());
                sb.Append("Email: ").AppendLine(EmailTextBox.Text.Trim());
                sb.Append("Card Ending With: ").AppendLine(CardNumber.Substring(CardNumber.Length - 4));
                sb.Append("Card Processor Error Message: ").AppendLine(response.ToString());

                Util.SendMail("*****@*****.**", "*****@*****.**", "Sacred Contracts Online Credit Card Not Accepted", sb.ToString(), false);
                throw new InvalidOperationException("Subscription failed: " + response.ToString());

            }
            return true;
        }
Esempio n. 11
0
        //-------------------------------------------------------------------------------------------
        /// <summary>
        /// Payment processing IVR              
        /// </summary>
        /// <param name="context"></param>
        public void Run(AppContext context)
        {
            WeavverEntityContainer data = new WeavverEntityContainer();
               Logistics_Organizations org = null;

               var session = context.Session;
               try
               {
                    session.Answer();

            Start:
                    // Welcome to the account payment system.
                    session.Execute("Playback", @"receivepayment\WelcomeToTheAccountPaymentSystem.wav");

                    // Figure out the caller's balance
                    decimal Balance = 0.0m;
                    bool hasBalance = Decimal.TryParse(session.GetVariable("Balance"), out Balance);
                    if (!hasBalance)
                    {
                         string OrganizationId = session.GetVariable("OrganizationId");
                         if (String.IsNullOrEmpty(OrganizationId))
                         {
            LogIn:
                              string UserCode = GetVariable(ref session, "UserCode", "number iterated", null);
                              string PassCode = GetVariable(ref session, "PassCode", "number iterated", null);

                              var user = (from x in data.System_Users
                                             where x.UserCode == UserCode &&
                                                  x.PassCode == PassCode
                                             select x).FirstOrDefault();

                              if (user != null)
                              {
                                   OrganizationId = user.OrganizationId.ToString();
                              }
                              else if (session.getState() == "CS_EXECUTE")
                              {
                                   session.Execute("Playback", @"receivepayment\AccountNotFound.wav");
                                   goto LogIn;
                              }
                              else
                              {
                                   session.SetVariable("PaymentStatus", "Failed");
                                   session.SetVariable("ResponseCode", "0");
                                   session.SetVariable("Message", "User did not log-in.");
                                   return;
                              }
                         }

                         Guid orgGuid = new Guid(OrganizationId);
                         org = (from orgs in data.Logistics_Organizations
                                where orgs.OrganizationId == orgGuid
                                select orgs).FirstOrDefault();

                         Balance = org.ReceivableBalance.Value;
                    }

                    // Play: Your account balance is:
                    session.Execute("Playback", @"receivepayment\YourAccountBalanceIs.wav");
                    session.Execute("Say", "en currency pronounced masculine " + Balance);

                    decimal PaymentAmount = Balance;
                    bool customPayment = false;
                    if (Balance == 0m)
                    {
                         string balanceIsEvenOption = PlayAndGet(ref session, 1, 1, @"YourBalanceIs0", null);
                         if (balanceIsEvenOption == "1")
                         {
                              customPayment = true;
                         }
                         else
                         {
                              session.SetVariable("PaymentStatus", "Failed");
                              session.SetVariable("ResponseCode", "0");
                              session.SetVariable("Message", "User has no balance to pay.");
                              return;
                         }
                    }
                    else
                    {
                         // Press 1 to pay your balance in full or 2 to enter another amount.
                         string entered = PlayAndGet(ref session, 1, 1, "Press1Or2", "^[1-2]$");
                         if (entered.Trim() == "2")
                         {
                              customPayment = true;
                         }
                    }
                    if (customPayment)
                    {
                         string enteredAmount = GetVariable(ref session, "PaymentAmount", "currency pronounced", null);
                         Decimal.TryParse(enteredAmount, out PaymentAmount);
                    }
                    string CardNumber     = GetVariable(ref session, "CardNumber", "number iterated", "^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13})$");
                    string CardExpiration = GetVariable(ref session, "CardExpiration", "number iterated", "^[0-9][0-9][0-9][0-9]$"); // MMDD
                    string CardCode       = GetVariable(ref session, "CardCode", "number iterated", "^[0-9][0-9][0-9][0-9]|[0-9][0-9][0-9]$"); // 1234|123

                    // Process Card
                    session.Execute("Playback", @"receivepayment\ProcessingPayment.wav");

                    var request = new AuthorizationRequest(CardNumber, CardExpiration, PaymentAmount, "Phone Payment", true);
                    //request.AddCustomer("", org.BillingAddressFK.Name, order.PrimaryContactNameLast, primaryAddress.Line1, primaryAddress.State, primaryAddress.ZipCode);

                    string referenceId = session.GetVariable("ReferenceId");
                    if (!String.IsNullOrEmpty(referenceId))
                    {
                         request.AddMerchantValue("ReferenceId", referenceId);
                    }
                    if (org != null)
                    {
                         request.AddMerchantValue("OrganizationId", org.Id.ToString());
                    }
                    var gate = new Gateway(ConfigurationManager.AppSettings["authorize.net_loginid"],
                                           ConfigurationManager.AppSettings["authorize.net_transactionkey"],
                                          // we use the reverse negative of testmode for safety in case the setting is missing from the app.config
                                          (ConfigurationManager.AppSettings["authorize.net_testmode"] != "false")
                                          );

                    var response = gate.Send(request, "Phone Payment");
                    if (response.Approved)
                    {
                         session.SetVariable("PaymentStatus", "Success");
                         session.SetVariable("PaymentAmount", PaymentAmount.ToString());
                         session.SetVariable("TransactionId", response.TransactionID);

                         session.Execute("Playback", @"receivepayment\PaymentSuccessYourTransactionCodeIs.wav");
                         session.Execute("Say", "en name_spelled iterated masculine " + response.TransactionID);
                    }
                    else
                    {
                         session.SetVariable("PaymentStatus", "Failed");
                         session.SetVariable("PaymentAmount", "0");
                         session.SetVariable("ResponseCode", response.ResponseCode);
                         session.SetVariable("Message", response.Message);

                         if (PlayAndGet(ref session, 1, 1, "PaymentFailure", null) == "1")
                         {
                              session.Execute("Playback", @"receivepayment\ThankYou.wav");

                              if (session.getState() == "CS_EXECUTE")
                                   goto Start;
                              else
                                   return;
                         }
                    }
               }
               catch (Exception ex)
               {
                    Debug(ref session, ex.Message);

                    session.SetVariable("PaymentStatus", "Failed");
                    session.SetVariable("Message", ex.Message);

                    WriteToLog("SystemError: " + ex.ToString());
                    session.Execute("Playback", @"receivepayment\SystemError.wav");
               }
        }
Esempio n. 12
0
        public TransactionResponse PayWithCreditCard(int peopleId, decimal amt, string cardnumber, string expires, string description, int tranid, string cardcode, string email, string first, string last, string addr, string addr2, string city, string state, string country, string zip, string phone)
        {
            var request = new AuthorizationRequest(cardnumber, expires, amt, description, includeCapture: true);

            request.AddCustomer(peopleId.ToString(), first, last, addr, state, zip);
            request.City = city; // hopefully will be resolved with https://github.com/AuthorizeNet/sdk-dotnet/pull/41
            request.Country = country;
            request.CardCode = cardcode;
            request.Phone = phone;
            request.Email = email;
            request.InvoiceNum = tranid.ToString();

            var response = Gateway.Send(request);

            return new TransactionResponse
            {
                Approved = response.Approved,
                AuthCode = response.AuthorizationCode,
                Message = response.Message,
                TransactionId = response.TransactionID
            };
        }
Esempio n. 13
0
        protected bool CreateCharge(out string auth_status,
                                     out string auth_code,
                                     out string auth_message,
                                     out string auth_response_code,
                                     out string auth_transaction_id,
                                     out decimal amt,
                                     decimal deposit,
                                     long transaction_id)
        {
            var apiKey = String.Empty;
            var transKey = String.Empty;

            var isTest = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["IsTestMode"]);

            if (isTest)
            {
                apiKey = System.Configuration.ConfigurationManager.AppSettings["TestAPIkEY"];
                transKey = System.Configuration.ConfigurationManager.AppSettings["TestTransactionKey"];
            }
            else
            {
                apiKey = System.Configuration.ConfigurationManager.AppSettings["APIKey"];
                transKey = System.Configuration.ConfigurationManager.AppSettings["TransactionKey"];
            }

            amt = deposit;

            var request = new AuthorizationRequest(CreditCardNumberTextBox.Text.Trim(),
                                                   MonthTextBox.Text.Trim() + YearTextBox.Text.Trim(),
                                                   amt,
                                                   "Myss.com Product Checkout - $" + amt,
                                                   AddressTextBox.Text.Trim(),
                                                   CityTextBox.Text.Trim(),
                                                   State.SelectedValue,
                                                   ZipTextBox.Text.Trim(),
                                                   CVVTextBox.Text.Trim(),
                                                   FirstNameTextBox.Text,
                                                   LastNameTextBox.Text);

            //Custom values that will be returned with the response
            //request.AddMerchantValue("email", EmailTextBox.Text);

            //order number
            request.AddInvoice(EmailTextBox.Text);

            //Shipping Address
            //request.AddShipping("id", "first", "last", "address", "state", "zip");

            //step 2 - create the gateway, sending in your credentials
            var gate = new Gateway(apiKey, transKey, isTest);

            //step 3 - make some money
            var response = gate.Send(request);

            if (!response.Approved)
            {
                string CardNumber = CreditCardNumberTextBox.Text.Trim();
                var sb = new StringBuilder();
                sb.Append("Name: ").Append(FirstNameTextBox.Text.Trim()).Append(" ").AppendLine(LastNameTextBox.Text.Trim());
                sb.Append("Email: ").AppendLine(EmailTextBox.Text.Trim());
                sb.Append("Card Ending With: ").AppendLine(CardNumber.Substring(CardNumber.Length - 4));
                sb.Append("Card Processor Error Message: ").AppendLine(response.ToString());

                auth_status = "declined";
                auth_code = response.AuthorizationCode;
                auth_message = response.Message;
                auth_response_code = response.ResponseCode;
                auth_transaction_id = response.TransactionID;
                try
                {
                    controller.UpateCMEDShopTransaction(transaction_id,
                                        auth_status,
                                        auth_code,
                                        auth_message,
                                        auth_response_code,
                                        auth_transaction_id);
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                Util.SendMail("*****@*****.**", "*****@*****.**", "Myss.com Purchase Credit Card Not Accepted", sb.ToString(), false);
                throw new CardAuthourize("Failed charging your credit card: error: [" + response.Message + "]  please try a different card");

            }

            auth_status = "approved";
            auth_code = response.AuthorizationCode;
            auth_message = response.Message;
            auth_response_code = response.ResponseCode;
            auth_transaction_id = response.TransactionID;

            return true;
        }
Esempio n. 14
0
        private bool CreateCharge(out int amt)
        {
            var apiKey = String.Empty;
            var transKey = String.Empty;

            var isTest = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["IsTestMode"]);

            if (isTest)
            {
                apiKey = System.Configuration.ConfigurationManager.AppSettings["TestAPIkEY"];
                transKey = System.Configuration.ConfigurationManager.AppSettings["TestTransactionKey"];
            }
            else
            {
                apiKey = System.Configuration.ConfigurationManager.AppSettings["APIKey"];
                transKey = System.Configuration.ConfigurationManager.AppSettings["TransactionKey"];
            }

            amt = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Cost"]);
            var discount = System.Configuration.ConfigurationManager.AppSettings[DicountCodeTextBox.Text.Trim()];

            if (discount != null)
                amt = Convert.ToInt32(discount);

            else if (DicountCodeTextBox.Text.Trim().Length > 0)
            {
                Util.DisplayAlert(this, "That is not a valid discount code");
                return false;
            }
            else if (PaymentDropDown.SelectedIndex == 2)
            {
                Util.DisplayAlert(this, "The graduate price requires a discount code");
                return false;
            }

            //step 1
            var request = new AuthorizationRequest(CreditCardNumberTextBox.Text.Trim(),
                                                   MonthTextBox.Text.Trim() + YearTextBox.Text.Trim(),
                                                   amt,
                                                   "Sacred Contracts Online Purchase - " + amt,
                                                   AddressTextBox.Text.Trim(),
                                                   CityTextBox.Text.Trim(),
                                                   State.SelectedValue,
                                                   ZipTextBox.Text.Trim(),
                                                   CVCTextBox.Text.Trim(),
                                                   FirstNameTextBox.Text,
                                                   LastNameTextBox.Text);

            //step 2 - create the gateway, sending in your credentials
            var gate = new Gateway(apiKey, transKey, isTest);

            //step 3 - make some money
            var response = gate.Send(request);

            if (!response.Approved)
            {
                string CardNumber = CreditCardNumberTextBox.Text.Trim();
                var sb = new StringBuilder();
                sb.Append("Name: ").Append(FirstNameTextBox.Text.Trim()).Append(" ").AppendLine(LastNameTextBox.Text.Trim());
                sb.Append("Email: ").AppendLine(EmailTextBox.Text.Trim());
                sb.Append("Card Ending With: ").AppendLine(CardNumber.Substring(CardNumber.Length - 4));
                sb.Append("Card Processor Error Message: ").AppendLine(response.ToString());

                Util.SendMail("*****@*****.**", "*****@*****.**", "Sacred Contracts Online Credit Card Not Accepted", sb.ToString(), false);
                throw new InvalidOperationException("Subscription failed: " + response.ToString());

                //Util.SendMail("*****@*****.**", "*****@*****.**", "Sacred Contracts Online Credit Card Not Accepted", response.Message, false);
                //throw new InvalidOperationException("Charge failed: " + response.Message);
            }
            return true;
        }
Esempio n. 15
0
        private bool CreateCharge()
        {
            var apiKey = System.Configuration.ConfigurationManager.AppSettings["APIKeySmithEvents"];
            var transKey = System.Configuration.ConfigurationManager.AppSettings["TransactionKeySmithEvents"];
            var isTest = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["IsTestModeSmithEvents"]);

            var amt = Convert.ToDecimal(PaymentDropDown.SelectedValue);

            var tour = Request.QueryString["tour"];
            var key = tour + "Title";
            var tour_title = System.Configuration.ConfigurationManager.AppSettings[key];
            var title = "Smith Events - " + tour_title.ToUpper();

            var request = new AuthorizationRequest(CreditCardNumberTextBox.Text.Trim(), MonthTextBox.Text.Trim() + YearTextBox.Text.Trim(), amt,
                   title + amt, AddressTextBox.Text.Trim(), CityTextBox.Text.Trim(), State.SelectedValue, ZipTextBox.Text.Trim(),
                   CVCTextBox.Text.Trim(), FirstNameTextBox.Text, LastNameTextBox.Text);

            //step 2 - create the gateway, sending in your credentials
            var gate = new Gateway(apiKey, transKey, isTest);

            //step 3 - make some money
            var response = gate.Send(request);
            if (!response.Approved)
            {
                Util.SendMail("*****@*****.**", "*****@*****.**", title, response.Message, false);
                throw new InvalidOperationException("Charge failed: " + response.Message);
            }
            return true;
        }
Esempio n. 16
0
        private IGatewayResponse ChargeConsumer(CartCheckOut checkOutDetails, CartSummary cartSummary)
        {
            var paymentRequest = new AuthorizationRequest(checkOutDetails.CardNumber,
                                                    string.Format("{0}{1}", checkOutDetails.ExpirationMonth, checkOutDetails.ExpirationYear),
                                                    cartSummary.TotalCost,
                                                    "Dirty Girl Cart Purchase",
                                                    true);

            paymentRequest.FirstName = checkOutDetails.CardHolderFirstname;
            paymentRequest.LastName = checkOutDetails.CardHolderLastname;
            paymentRequest.Zip = checkOutDetails.CardHolderZipCode;
            paymentRequest.CardCode = checkOutDetails.CCVNumber;

            var totalTax = 0.0M;
            foreach (var item in cartSummary.CartItems)
            {
                paymentRequest.AddLineItem(item.PurchaseItemId.ToString(), item.ItemName, item.DiscountDescription, 1, item.ItemTotal, item.Taxable);
                if (item.Taxable)
                    totalTax += (item.StateTax + item.LocalTax);
            }

            paymentRequest.AddTax(totalTax);

            var gateway = new Gateway(DirtyGirlServiceConfig.Settings.PaymentGatewayId, DirtyGirlServiceConfig.Settings.PaymentGatewayKey, true);
            gateway.TestMode = DirtyGirlServiceConfig.Settings.PaymentTestMode;

            return gateway.Send(paymentRequest);
        }
Esempio n. 17
0
        private bool CreateCharge(out int amt, int deposit)
        {
            var apiKey = String.Empty;
            var transKey = String.Empty;

            var isTest = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["IsTestMode"]);

            if (isTest)
            {
                apiKey = System.Configuration.ConfigurationManager.AppSettings["TestAPIkEY"];
                transKey = System.Configuration.ConfigurationManager.AppSettings["TestTransactionKey"];
            }
            else
            {
                apiKey = System.Configuration.ConfigurationManager.AppSettings["APIKey"];
                transKey = System.Configuration.ConfigurationManager.AppSettings["TransactionKey"];
            }

            amt = deposit;

            var request = new AuthorizationRequest(CreditCardNumberTextBox.Text.Trim(),
                                                   MonthTextBox.Text.Trim() + YearTextBox.Text.Trim(),
                                                   amt,
                                                   "Myss.com Reflections Classes - " + amt,
                                                   AddressTextBox.Text.Trim(),
                                                   CityTextBox.Text.Trim(),
                                                   State.SelectedValue,
                                                   ZipTextBox.Text.Trim(),
                                                   CVVTextBox.Text.Trim(),
                                                   FirstNameTextBox.Text,
                                                   LastNameTextBox.Text);

            //Custom values that will be returned with the response
            //request.AddMerchantValue("email", EmailTextBox.Text);

            //order number
            request.AddInvoice(EmailTextBox.Text);

            //Shipping Address
            //request.AddShipping("id", "first", "last", "address", "state", "zip");

            //step 2 - create the gateway, sending in your credentials
            var gate = new Gateway(apiKey, transKey, isTest);

            //step 3 - make some money
            var response = gate.Send(request);

            if (!response.Approved)
            {
                string CardNumber = CreditCardNumberTextBox.Text.Trim();
                var sb = new StringBuilder();
                sb.Append("Name: ").Append(FirstNameTextBox.Text.Trim()).Append(" ").AppendLine(LastNameTextBox.Text.Trim());
                sb.Append("Email: ").AppendLine(EmailTextBox.Text.Trim());
                sb.Append("Card Ending With: ").AppendLine(CardNumber.Substring(CardNumber.Length - 4));
                sb.Append("Card Processor Error Message: ").AppendLine(response.ToString());

                Util.SendMail("*****@*****.**", "*****@*****.**", "Myss.com Reflections Classes Credit Card Not Accepted", sb.ToString(), false);
                lblErrorMessage.Text = "Unable to process your credit card. Please verify the information or try another card. ";
                throw new InvalidOperationException("Subscription failed: " + response.ToString());

            }
            return true;
        }
        public IGatewayResponse cardNotPresent(string cardNumber, string expMonthYear, decimal amount, string description)
        {
            //Step 1 Create the request
            var request = new AuthorizationRequest(cardNumber, expMonthYear, amount, description);

            //step 2 - create the gateway, sending in your credentials
            var gate = new Gateway(apiKey, transactionKey, developerTesting);

            //step 3 - make some money
            var response = gate.Send(request);

            return response;
        }
        public ActionResult Authorize(int id = 0)
        {
            Customer c = new Customer { ID = id };
            c.Get();
            Cart currentCart = c.Carts.Where(x => x.payment_id == 0).First<Cart>();
            Settings settings = ViewBag.settings;

            decimal amount = currentCart.getTotal();
            string cardnum = Request.Form["cardnumber"];
            string month = Request.Form["expiremonth"];
            string year = Request.Form["expireyear"];
            string cvv = Request.Form["cvv"];
            string first = Request.Form["first"];
            string last = Request.Form["last"];

            //step 1 - create the request
            IGatewayRequest request = new AuthorizationRequest(cardnum, month + year, amount, "Transaction");

            //These are optional calls to the API
            request.AddCardCode(cvv);

            //Customer info - this is used for Fraud Detection
            request.AddCustomer(c.ID.ToString(), first, last, currentCart.Billing.street1 + ((currentCart.Billing.street2 != "") ? " " + currentCart.Billing.street2 : ""), currentCart.Billing.State1.abbr, currentCart.Billing.postal_code);

            //order number
            //request.AddInvoice("invoiceNumber");

            //Custom values that will be returned with the response
            //request.AddMerchantValue("merchantValue", "value");

            //Shipping Address
            request.AddShipping(c.ID.ToString(), currentCart.Shipping.first, currentCart.Shipping.last, currentCart.Shipping.street1 + ((currentCart.Shipping.street2 != "") ? " " + currentCart.Shipping.street2 : ""), currentCart.Shipping.State1.abbr, currentCart.Shipping.postal_code);

            //step 2 - create the gateway, sending in your credentials and setting the Mode to Test (boolean flag)
            //which is true by default
            //this login and key are the shared dev account - you should get your own if you
            //want to do more testing
            bool testmode = false;
            if (settings.Get("AuthorizeNetTestMode").Trim() == "true") {
                testmode = true;
            }

            Gateway gate = new Gateway(settings.Get("AuthorizeNetLoginKey"), settings.Get("AuthorizeNetTransactionKey"), testmode);

            //step 3 - make some money
            IGatewayResponse response = gate.Send(request);
            if (response.Approved) {
                currentCart.AddPayment("credit card", response.AuthorizationCode,"Complete");
                currentCart.SendConfirmation();
                int cartid = currentCart.ID;
                return RedirectToAction("Step6", new { id = cartid });
            } else {
                TempData["message"] = response.Message;
                return RedirectToAction("Step5", new { id = c.ID });
            }
        }
Esempio n. 20
0
        private string SendAuthOnly(decimal amount, bool returnTransID)
        {
            string responseString = "1|1|1|This transaction has been approved.|P9A0ET|Y|2207700131||AuthOnly transaction approved testing|11.21|CC|auth_only||||||||||||||||||||||||||C4DB0F58C8BE75212AB0261BF7F1BE21||2|||||||||||XXXX1111|Visa||||||||||||||||";
            LocalRequestObject.ResponseString = responseString;

            Gateway target = new Gateway(ApiLogin, TransactionKey, true);

            IGatewayRequest request = new AuthorizationRequest("4111111111111111", "0224", amount, "AuthOnly transaction approved testing", false);
            string description = "Auth only transaction approved testing";

            IGatewayResponse response = target.Send(request, description);

            if (response.Approved)
            {
                if (returnTransID)
                {
                    return response.TransactionID;
                }
                else
                {
                    return response.AuthorizationCode;
                }
            }
            else
            {
                return "";
            }
        }
Esempio n. 21
0
        public ActionResult Index(Donation donation)
        {
            var request = new AuthorizationRequest(donation.CardNumber, donation.ExpMonth + donation.ExpYear, donation.Amount,
                "Sponsor an AFSer");

            request.AddCustomer("", donation.FirstName, donation.LastName, donation.Address, donation.State,
                                donation.Zip);

            request.City = donation.City;
            request.Email = donation.Email;

            using (var context = new AFSAdminContext())
            {
                var widget = context.StudentWidgets.Find(donation.StudentWidget_StudentWidgetId);
                request.ShipToFirstName = widget.FirstName;
                request.ShipToLastName = widget.LastName;
            }

            //step 2 - create the gateway, sending in your credentials
            //var gate = new Gateway("6zz6m5N4Et", "9V9wUv6Yd92t27t5", true);
            var gate = new Gateway("7f5SDz7huZ", "8A44F37ee89KqBDz", false);

            //step 3 - make some money
            var response = gate.Send(request);

            if (response.Approved)
            {
                donation.TransactionId = response.TransactionID;
                using (var context = new AFSAdminContext())
                {
                    var widget = context.StudentWidgets.Find(donation.StudentWidget_StudentWidgetId);
                    donation.DonationId = Guid.NewGuid();
                    donation.StudentWidget = widget;
                    donation.DateOfTransaction = DateTime.Now;
                    donation.StudentWidget.AmountRaised += donation.Amount;
                    context.Donations.Add(donation);
                    context.SaveChanges();

                }

                using (var svc = new WebserviceFundAFSerSoapClient())
                {
                    XElement rsp = svc.AFSWidgetPaymentDetails("afserwidget", "globalwidgerasfer2012"
                                                                    , donation.StudentWidget.ServiceId.ToString()
                                                                    , donation.StudentWidget.StudentWidgetId.ToString()
                                                                    , donation.TransactionId
                                                                    , donation.DonationId.ToString()
                                                                    , donation.FirstName
                                                                    , donation.LastName
                                                                    , donation.Address
                                                                    , donation.City
                                                                    , donation.State
                                                                    , donation.Zip
                                                                    , donation.Email
                                                                    , donation.Amount.ToString()
                                                                    , donation.Message);
                    TempData["WSResponse"] = rsp;
                }

                TempData["Email"] = donation.Email;
                TempData["Name"] = donation.StudentWidget.FirstName;
                TempData["Amount"] = donation.Amount;
                return RedirectToAction("Reciept");
            }

            using (var context = new AFSAdminContext())
            {
                var widget = context.StudentWidgets.Find(donation.StudentWidget_StudentWidgetId);
                donation.StudentWidget = widget;
                ViewBag.WidgetName = widget.FirstName;
            }
            ViewBag.ErrorMsg = "Error code: " + response.ResponseCode + " Message: " + response.Message;
            return View(donation);
        }
        public override bool ProcessPayment(Payment payment, ref string message)
        {
            var info = payment as CreditCardPayment;

            if (ReferenceEquals(info, null))
            {
                payment.Status = PaymentStatus.Failed.ToString();
                message = "AuthorizeNet gateway supports only CreditCardPayment";
                return false;
            }

            string[] validateSettings = { "MerchantLogin", "MerchantPassword" };

            foreach (var validateSetting in validateSettings)
            {
                if (!Settings.ContainsKey(validateSetting) || string.IsNullOrWhiteSpace(Settings[validateSetting]))
                {
                    payment.Status = PaymentStatus.Failed.ToString();
                    message = string.Format("{0} not configured", validateSetting);
                    return false;
                }
            }

            var transactionType = (TransactionType)Enum.Parse(typeof(TransactionType), info.TransactionType);
            payment.Status = PaymentStatus.Processing.ToString();

            var gateway = new Gateway(Settings["MerchantLogin"], Settings["MerchantPassword"]);

            bool isTestMode;
            if (Settings.ContainsKey("TestMode") && bool.TryParse(Settings["TestMode"], out isTestMode))
            {
                gateway.TestMode = isTestMode;
            }

            var description = string.Format("{0} transaction for order id {1}", transactionType, info.OrderForm.OrderGroupId);
            IGatewayRequest request = null;

            switch (transactionType)
            {
                case TransactionType.Authorization:
                case TransactionType.Sale:
                    request = new AuthorizationRequest(info.CreditCardNumber,
                        string.Format("{0}{1}", info.CreditCardExpirationMonth, info.CreditCardExpirationYear),
                        info.Amount,
                        description,
                        transactionType == TransactionType.Sale);
                    break;
                case TransactionType.Capture:
                    request = new PriorAuthCaptureRequest(info.Amount, info.ValidationCode);
                    break;
                case TransactionType.Credit:
                    request = new CreditRequest(info.ValidationCode, info.Amount, info.CreditCardNumber);
                    break;
                case TransactionType.Void:
                    request = new VoidRequest(info.ValidationCode);
                    break;
            }

            if (request == null)
            {
                payment.Status = PaymentStatus.Failed.ToString();
                message = string.Format("Unsupported transation type {0}", transactionType);
                return false;
            }

            request.AddCardCode(info.CreditCardSecurityCode);

            var invoice = info.OrderForm.OrderGroupId;

            var order = info.OrderForm.OrderGroup as Order;
            if (order != null)
            {
                invoice = order.TrackingNumber;
            }

            request.AddInvoice(invoice);
            request.AddTax(info.OrderForm.TaxTotal);

            // Find the address
            var address = info.OrderForm.OrderGroup.OrderAddresses
                .FirstOrDefault(a => String.Compare(a.OrderAddressId, info.BillingAddressId, StringComparison.OrdinalIgnoreCase) == 0);

            if (address != null)
            {
                request.AddCustomer(address.Email, address.FirstName, address.LastName,
                    address.Line1 + " " + address.Line2, address.StateProvince, address.PostalCode);
            }

            //foreach (var lineItem in info.OrderForm.LineItems)
            //{
            //    request.AddLineItem(lineItem.LineItemId, lineItem.DisplayName, lineItem.Description,
            //        (int)lineItem.Quantity, lineItem.PlacedPrice, false);
            //}


            try
            {
                var response = gateway.Send(request, description);

                if (!response.Approved)
                {
                    payment.Status = PaymentStatus.Denied.ToString();
                    message = "Transaction Declined: " + response.Message;
                    return false;
                }
                info.StatusCode = response.ResponseCode;
                info.StatusDesc = response.Message;
                info.ValidationCode = response.TransactionID;
                info.AuthorizationCode = response.AuthorizationCode;

                // transaction is marked as completed every time the payment operation succeeds even if it is void transaction type
                payment.Status = PaymentStatus.Completed.ToString();          
            }
            catch (Exception ex)
            {
                payment.Status = PaymentStatus.Failed.ToString();
                throw new ApplicationException(ex.Message);
            }

            return true;

        }