/// <summary> /// Get the users billing address by email /// </summary> /// <param name="userEmail"></param> /// <returns></returns> private async Task <customerAddressType> GetsBillingAddress(string userEmail) { // you can pull this data from teh db the individual data from the order/cart itself Order order = await _order.GetOrder(userEmail); customerAddressType address = new customerAddressType { firstName = order.FirstName, lastName = order.LastName, address = order.Address, city = order.City, zip = order.ZipCode }; return(address); }
/// <summary> /// Creates an API type for use with outbound requests to the Gateway. Mostly for internal use. /// </summary> /// <returns></returns> public customerAddressType ToAPIType() { var result = new customerAddressType(); result.address = this.Street; result.city = this.City; result.company = this.Company; result.country = this.Country; result.faxNumber = this.Fax; result.firstName = this.First; result.lastName = this.Last; result.phoneNumber = this.Phone; result.state = this.State; result.zip = this.Zip; return(result); }
public static void Run(String ApiLoginID, String ApiTransactionKey) { Console.WriteLine("CreateCustomerShippingAddress Sample"); ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment = AuthorizeNet.Environment.SANDBOX; ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = new merchantAuthenticationType() { name = ApiLoginID, ItemElementName = ItemChoiceType.transactionKey, Item = ApiTransactionKey, }; customerAddressType officeAddress = new customerAddressType(); officeAddress.firstName = "Chris"; officeAddress.lastName = "brown"; officeAddress.address = "1200 148th AVE NE"; officeAddress.city = "NorthBend"; officeAddress.zip = "92101"; var request = new createCustomerShippingAddressRequest { customerProfileId = "36537239", address = officeAddress, }; //Prepare Request var controller = new createCustomerShippingAddressController(request); controller.Execute(); //Send Request to EndPoint createCustomerShippingAddressResponse response = controller.GetApiResponse(); if (response != null && response.messages.resultCode == messageTypeEnum.Ok) { if (response != null && response.messages.message != null) { Console.WriteLine("Success, customerAddressId : " + response.customerAddressId); } } else { Console.WriteLine("Error: " + response.messages.message[0].code + " " + response.messages.message[0].text); } }
/// <summary> /// Running authorization net /// </summary> /// <param name="addressType">Addresstype object that carries user's information</param> /// <param name="totalAmount">total amount that user owes</param> /// <returns>boolean if the payment went through</returns> public bool Run(customerAddressType addressType, decimal totalAmount) { ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment = AuthorizeNet.Environment.SANDBOX; ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = new merchantAuthenticationType { name = _config["An-ApiId"], ItemElementName = ItemChoiceType.transactionKey, Item = _config["An-TransactionKey"] }; var CreditCard = new creditCardType { cardNumber = "4111111111111111", expirationDate = "0521", cardCode = "102" }; var paymentType = new paymentType { Item = CreditCard }; var transactionRequest = new transactionRequestType { transactionType = transactionTypeEnum.authCaptureTransaction.ToString(), amount = totalAmount, payment = paymentType, billTo = addressType }; var request = new createTransactionRequest { transactionRequest = transactionRequest }; var controller = new createTransactionController(request); controller.Execute(); var response = controller.GetApiResponse(); if (response != null) { if (response.messages.resultCode == messageTypeEnum.Ok) { return(true); } } return(false); }
public async Task<ActionResult> AddOrder(HomeViewModel model) { //submit the order to processor ChargeCreditCardClient authnetChargeClient = new ChargeCreditCardClient(); creditCardType creditCard = new creditCardType { cardNumber = model.CreditCard.CardNumber, expirationDate = String.Format("{0:00}", model.CreditCard.ExpMonth) + String.Format("{0:00}", model.CreditCard.ExpYear), cardCode = model.CreditCard.CardCode }; customerAddressType billingAddress = new customerAddressType { firstName = model.CreditCard.BillFirstName, lastName = model.CreditCard.BillLastName, address = model.CreditCard.BillStreet, city = model.CreditCard.BillCity, zip = model.CreditCard.BillZip }; lineItemType[] lineItems = new lineItemType[model.EditOrder.Items.Count + 3]; for (int i = 0; i < model.EditOrder.Items.Count; i++) { lineItems[i] = new lineItemType { itemId = i.ToString(), name = model.EditOrder.Items[i].ProductName + ", " + model.EditOrder.Items[i].ProductShortDescr, quantity = model.EditOrder.Items[i].Quantity, unitPrice = model.EditOrder.Items[i].UnitPrice }; } lineItems[model.EditOrder.Items.Count] = new lineItemType { itemId = model.EditOrder.Items.Count.ToString(), name = "Tax", quantity = 1m, unitPrice = model.EditOrder.Tax }; lineItems[model.EditOrder.Items.Count + 1] = new lineItemType { itemId = (model.EditOrder.Items.Count + 1).ToString(), name = "Shipping and Handling", quantity = 1m, unitPrice = model.EditOrder.ShipHand }; lineItems[model.EditOrder.Items.Count + 2] = new lineItemType { itemId = (model.EditOrder.Items.Count + 2).ToString(), name = "Adjustment", quantity = 1m, unitPrice = model.EditOrder.Adjustment }; createTransactionResponse response = authnetChargeClient.RunCharge(authorizeNetApiLoginID, authorizeNetApiTransactionKey, creditCard, billingAddress, lineItems, model.EditOrder.Total); model.ResponseCode = response.transactionResponse.responseCode; model.TransactionId = response.transactionResponse.transId; model.AuthorizationCode = response.transactionResponse.authCode; //save the order in the Db model.EditOrder.CardLastFour = model.CreditCard.CardNumber.Substring(model.CreditCard.CardNumber.Length - 4); model.EditOrder.TransactionId = model.TransactionId; model.EditOrder.ResponseCode = model.ResponseCode; model.EditOrder.AuthorizationCode = model.AuthorizationCode; model.Orders = await repository.AddOrderAsync(model.EditOrder, true); return View("Orders", model); }
/// <summary> /// Method that takes in an address and UserViewModel to create our /// transaction request. Since we are only processing fake cards /// we are inputting a test card for the user in the method /// </summary> /// <param name="uvm">UserViewModel</param> /// <param name="address">Address</param> /// <returns>Transaction Request</returns> public transactionRequestType TransactionRequest(UserViewModel uvm, customerAddressType address) { var CreditCard = new creditCardType { cardNumber = "4111111111111111", expirationDate = "0720" }; var PaymentType = new paymentType { Item = CreditCard }; var TransactionRequest = new transactionRequestType { transactionType = transactionTypeEnum.authCaptureTransaction.ToString(), amount = uvm.Order.TotalPrice, payment = PaymentType, billTo = address, lineItems = CreateLineItems(uvm), }; return(TransactionRequest); }
/// <summary> /// Process a payment /// </summary> /// <param name="processPaymentRequest">Payment info required for an order processing</param> /// <returns>Process payment result</returns> public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest) { var result = new ProcessPaymentResult(); var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId); PrepareAuthorizeNet(); var creditCard = new creditCardType { cardNumber = processPaymentRequest.CreditCardNumber, expirationDate = processPaymentRequest.CreditCardExpireMonth.ToString("D2") + processPaymentRequest.CreditCardExpireYear, cardCode = processPaymentRequest.CreditCardCvv2 }; //standard api call to retrieve response var paymentType = new paymentType { Item = creditCard }; transactionTypeEnum transactionType; switch (_authorizeNetPaymentSettings.TransactMode) { case TransactMode.Authorize: transactionType = transactionTypeEnum.authOnlyTransaction; break; case TransactMode.AuthorizeAndCapture: transactionType = transactionTypeEnum.authCaptureTransaction; break; default: throw new NopException("Not supported transaction mode"); } var billTo = new customerAddressType { firstName = customer.BillingAddress.FirstName, lastName = customer.BillingAddress.LastName, email = customer.BillingAddress.Email, address = customer.BillingAddress.Address1, city = customer.BillingAddress.City, zip = customer.BillingAddress.ZipPostalCode }; if (!string.IsNullOrEmpty(customer.BillingAddress.Company)) { billTo.company = customer.BillingAddress.Company; } if (customer.BillingAddress.StateProvince != null) { billTo.state = customer.BillingAddress.StateProvince.Abbreviation; } if (customer.BillingAddress.Country != null) { billTo.country = customer.BillingAddress.Country.TwoLetterIsoCode; } var transactionRequest = new transactionRequestType { transactionType = transactionType.ToString(), amount = Math.Round(processPaymentRequest.OrderTotal, 2), payment = paymentType, currencyCode = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode, billTo = billTo, customerIP = _webHelper.GetCurrentIpAddress(), order = new orderType { //x_invoice_num is 20 chars maximum. hece we also pass x_description invoiceNumber = processPaymentRequest.OrderGuid.ToString().Substring(0, 20), description = string.Format("Full order #{0}", processPaymentRequest.OrderGuid) } }; var request = new createTransactionRequest { transactionRequest = transactionRequest }; // instantiate the contoller that will call the service var controller = new createTransactionController(request); controller.Execute(); // get the response from the service (errors contained if any) var response = GetApiResponse(controller, result.Errors); //validate if (response == null) { return(result); } if (_authorizeNetPaymentSettings.TransactMode == TransactMode.Authorize) { result.AuthorizationTransactionId = response.transactionResponse.transId; result.AuthorizationTransactionCode = string.Format("{0},{1}", response.transactionResponse.transId, response.transactionResponse.authCode); } if (_authorizeNetPaymentSettings.TransactMode == TransactMode.AuthorizeAndCapture) { result.CaptureTransactionId = string.Format("{0},{1}", response.transactionResponse.transId, response.transactionResponse.authCode); } result.AuthorizationTransactionResult = string.Format("Approved ({0}: {1})", response.transactionResponse.responseCode, response.transactionResponse.messages[0].description); result.AvsResult = response.transactionResponse.avsResultCode; result.NewPaymentStatus = _authorizeNetPaymentSettings.TransactMode == TransactMode.Authorize ? PaymentStatus.Authorized : PaymentStatus.Paid; return(result); }
public TransactionResponse ChargeCredit(PaymentModel payment) { // determine run Environment to SANDBOX for developemnt level ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment = AuthorizeNet.Environment.SANDBOX; // define the merchant information (authentication / transaction id) ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = new merchantAuthenticationType() { name = apiLoginId, ItemElementName = ItemChoiceType.transactionKey, Item = transactionKey, }; var creditCard = new creditCardType { cardNumber = payment.CardNumber, expirationDate = payment.Month + payment.Year, cardCode = payment.CardCode, }; var bilingAddress = new customerAddressType { firstName = payment.FirstName, lastName = payment.LastName, city = payment.Address1, address = payment.Address2, zip = payment.PostCode }; //standard api call to retrieve response var paymentType = new paymentType { Item = creditCard }; //getting payment that student paying var studentAmount = new PaymentModel(); var studentID = new Student(); //Add line Items you pay to obtain these var lineItems = new lineItemType[1]; lineItems[0] = new lineItemType { itemId = studentID.ID.ToString(), name = "Tution Fees", quantity = 1, unitPrice = studentAmount.Amount, taxRate = 7.5M, totalAmount = studentAmount.Amount }; var transactionRequest = new transactionRequestType { transactionType = transactionTypeEnum.authCaptureTransaction.ToString(),// charge the card amount = Convert.ToDecimal(payment.Amount), payment = paymentType, billTo = bilingAddress, lineItems = lineItems }; var request = new createTransactionRequest { transactionRequest = transactionRequest }; // instantiate the contoller that will call the service var controller = new createTransactionController(request); controller.Execute(); var resCode = controller.GetResultCode(); var resAll = controller.GetResults(); //get the response from the service (errors contained if any) var response = controller.GetApiResponse(); //validate TransactionResponse result = new TransactionResponse(); if (response != null) { result.ResultCode = response.messages.resultCode; if (response.messages.resultCode == messageTypeEnum.Ok) { if (response.transactionResponse.messages != null) { result.TransId = response.transactionResponse.transId; result.ResponseCode = response.transactionResponse.responseCode; result.MessageCode = response.transactionResponse.messages[0].code; result.Description = response.transactionResponse.messages[0].description; result.AuthCode = response.transactionResponse.authCode; result.AmountPaid = payment.Amount; } else { if (response.transactionResponse.errors != null) { result.ErrorCode = response.transactionResponse.errors[0].errorCode; result.ErrorText = response.transactionResponse.errors[0].errorText; } } } else { if (response.transactionResponse != null && response.transactionResponse.errors != null) { result.ErrorCode = response.transactionResponse.errors[0].errorCode; result.ErrorText = response.transactionResponse.errors[0].errorText; } else { result.ErrorCode = response.messages.message[0].code; result.ErrorText = response.messages.message[0].text; } } } else { //result.errorCode = "NONE"; //result.errorText = "Failed Transaction, Unknown Error"; ANetApiResponse errorResponse = controller.GetErrorResponse(); result.ErrorText = errorResponse.messages.message[0].text; result.ErrorCode = errorResponse.messages.message[0].code; result.ResultCode = messageTypeEnum.Error; } return(result); }
public void SetUp() { MockContext = new MockFactory(); //initialize counter Counter = _random.Next(1, (int)(Math.Pow(2, 24))); CounterStr = GetRandomString(""); _now = DateTime.UtcNow; _nowString = _now.ToString(DateFormat); _pastDate = _now.AddMonths(-1); _nowDate = _now; _futureDate = _now.AddMonths(1); CustomMerchantAuthenticationType = new merchantAuthenticationType { name = ApiLoginIdKey, ItemElementName = ItemChoiceType.transactionKey, Item = TransactionKey, }; // merchantAuthenticationType.setSessionToken(GetRandomString("SessionToken")); // merchantAuthenticationType.setPass_word(GetRandomString("Pass_word")); // merchantAuthenticationType.setMobileDeviceId(GetRandomString("MobileDevice")); // ImpersonationAuthenticationType impersonationAuthenticationType = new ImpersonationAuthenticationType(); // impersonationAuthenticationType.setPartnerLoginId(CnpApiLoginIdKey); // impersonationAuthenticationType.setPartnerTransactionKey(CnpTransactionKey); // merchantAuthenticationType.setImpersonationAuthentication(impersonationAuthenticationType); CustomerProfileType = new customerProfileType { merchantCustomerId = GetRandomString("Customer"), description = GetRandomString("CustomerDescription"), email = CounterStr + "*****@*****.**", }; //make sure these elements are initialized by calling get as it uses lazy initialization var paymentProfiles = CustomerProfileType.paymentProfiles; var addresses = CustomerProfileType.shipToList; CreditCardOne = new creditCardType { cardNumber = "4111111111111111", expirationDate = "2038-12", }; // creditCardOne.setCardCode(""); BankAccountOne = new bankAccountType { accountType = bankAccountTypeEnum.savings, routingNumber = "125000000", accountNumber = GetRandomString("A/C#"), nameOnAccount = GetRandomString("A/CName"), echeckType = echeckTypeEnum.WEB, bankName = GetRandomString("Bank"), checkNumber = CounterStr, }; TrackDataOne = new creditCardTrackType { ItemElementName = ItemChoiceType1.track1, Item = GetRandomString("Track1"), //trackDataOne.setTrack2(GetRandomString("Track2")); }; EncryptedTrackDataOne = new encryptedTrackDataType { FormOfPayment = new KeyBlock(), }; //keyBlock.setValue(value); PayPalOne = new payPalType { successUrl = GetRandomString("https://success.anet.net"), cancelUrl = GetRandomString("https://cancel.anet.net"), paypalLc = GetRandomString("Lc"), paypalHdrImg = GetRandomString("Hdr"), paypalPayflowcolor = GetRandomString("flowClr"), payerID = GetRandomString("PayerId"), }; PaymentOne = new paymentType { Item = CreditCardOne }; //paymentOne.setBankAccount(bankAccountOne); //paymentOne.setTrackData(trackDataOne); //paymentOne.setEncryptedTrackData(encryptedTrackDataOne); //paymentOne.setPayPal( payPalOne); // driversLicenseOne = new DriversLicenseType(); // driversLicenseOne.setNumber(GetRandomString("DLNumber")); // driversLicenseOne.setState(GetRandomString("WA")); // driversLicenseOne.setDateOfBirth(nowString); CustomerAddressOne = new customerAddressType { firstName = GetRandomString("FName"), lastName = GetRandomString("LName"), company = GetRandomString("Company"), address = GetRandomString("StreetAdd"), city = "Bellevue", state = "WA", zip = "98000", country = "USA", phoneNumber = FormatToPhone(Counter), faxNumber = FormatToPhone(Counter + 1), }; CustomerPaymentProfileOne = new customerPaymentProfileType { customerType = customerTypeEnum.individual, payment = PaymentOne, }; // customerPaymentProfileOne.setBillTo(customerAddressOne); // customerPaymentProfileOne.setDriversLicense(driversLicenseOne); // customerPaymentProfileOne.setTaxId(GetRandomString("XX")); CustomerOne = new customerType { type = customerTypeEnum.individual, id = GetRandomString("Id"), email = CounterStr + "*****@*****.**", phoneNumber = FormatToPhone(Counter), faxNumber = FormatToPhone(Counter + 1), driversLicense = DriversLicenseOne, taxId = "911011011", }; CustomerTwo = new customerType(); var interval = new paymentScheduleTypeInterval { length = 1, unit = ARBSubscriptionUnitEnum.months, }; OrderType = new orderType() { //TODO ADD VALIDATION ON INVOICE LENGTH invoiceNumber = GetRandomString("Inv:"), description = GetRandomString("Description"), }; NameAndAddressTypeOne = new nameAndAddressType { firstName = GetRandomString("FName"), lastName = GetRandomString("LName"), company = GetRandomString("Company"), address = GetRandomString("Address"), city = GetRandomString("City"), state = GetRandomString("State"), zip = "98004", country = "USA", }; NameAndAddressTypeTwo = new nameAndAddressType { firstName = GetRandomString("FName"), lastName = GetRandomString("LName"), company = GetRandomString("Company"), address = GetRandomString("Address"), city = GetRandomString("City"), state = GetRandomString("State"), zip = "98004", country = "USA", }; PaymentScheduleTypeOne = new paymentScheduleType { interval = interval, startDate = _nowDate, totalOccurrences = 5, trialOccurrences = 0, }; ArbSubscriptionOne = new ARBSubscriptionType { amount = SetValidSubscriptionAmount(Counter), billTo = NameAndAddressTypeOne, customer = CustomerOne, name = GetRandomString("Name"), order = OrderType, payment = PaymentOne, paymentSchedule = PaymentScheduleTypeOne, shipTo = NameAndAddressTypeOne, trialAmount = SetValidSubscriptionAmount(0), }; CustomerDataOne = new customerDataType { driversLicense = CustomerOne.driversLicense, email = CustomerOne.email, id = CustomerOne.id, taxId = CustomerOne.taxId, type = CustomerOne.type, }; RefId = CounterStr; }
//string ApiLoginID = Constants.API_LOGIN_ID; //string ApiTransactionKey = Constants.TRANSACTION_KEY; public static ANetApiResponse Run(PaymentViewModel PaymentVM) { ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment = AuthorizeNet.Environment.SANDBOX; // define the merchant information (authentication / transaction id) ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = new merchantAuthenticationType() { name = Constants.API_LOGIN_ID, ItemElementName = ItemChoiceType.transactionKey, Item = Constants.TRANSACTION_KEY, }; var creditCard = new creditCardType { cardNumber = PaymentVM.sCreditCardNumber, expirationDate = PaymentVM.sExpiryMonth.ToString() + PaymentVM.sExpiryYear.ToString(), cardCode = PaymentVM.sCCV.ToString() }; var billingAddress = new customerAddressType { firstName = PaymentVM.sCardName, lastName = "", address = PaymentVM.BillingAddressVM[0].StreetName, city = PaymentVM.BillingAddressVM[0].City, zip = PaymentVM.BillingAddressVM[0].Zip }; //standard api call to retrieve response var paymentType = new paymentType { Item = creditCard }; // Add line Items var lineItems = new lineItemType[1]; lineItems[0] = new lineItemType { itemId = PaymentVM.iPlanID.ToString(), name = "Test", quantity = 1, unitPrice = PaymentVM.dAmount }; var transactionRequest = new transactionRequestType { transactionType = transactionTypeEnum.authCaptureTransaction.ToString(), // charge the card amount = PaymentVM.dAmount, payment = paymentType, billTo = billingAddress, lineItems = lineItems }; var request = new createTransactionRequest { transactionRequest = transactionRequest }; // instantiate the contoller that will call the service var controller = new createTransactionController(request); controller.Execute(); // get the response from the service (errors contained if any) var response = controller.GetApiResponse(); return(response); }
/// <summary> /// This is the method that charges the user's credit card. /// </summary> /// <param name="cvm">The information we use to charge the credit card</param> /// <returns>The response from the api</returns> public ANetApiResponse RunCard(CheckoutViewModel cvm) { //make sure it's running in the sandbox environment// ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment = AuthorizeNet.Environment.SANDBOX; //define the merchant information (authentication / transaction key) ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = new merchantAuthenticationType() { name = Configuration["Authorize:ApiLoginID"], ItemElementName = ItemChoiceType.transactionKey, Item = Configuration["Authorize:ApiTransactionKey"] }; long cardNumber = (long)cvm.Card; //Temp credit card to use for tests var creditCard = new creditCardType { cardNumber = cardNumber.ToString(), expirationDate = "0918", cardCode = "123" }; //address to refactor var billingAddress = new customerAddressType { firstName = cvm.FirstName, lastName = cvm.LastName, address = cvm.Street, city = cvm.City, zip = "98119" }; //Add line Items orders // lineItemType[] MakeLineItems = new lineItemType[cvm.Order.BasketItems.Count]; for (int i = 0; i < MakeLineItems.Length; i++) { MakeLineItems[i] = new lineItemType { itemId = cvm.Order.BasketItems[i].Product.ID.ToString(), name = cvm.Order.BasketItems[i].Product.Name, quantity = cvm.Order.BasketItems[i].Quantity, unitPrice = cvm.Order.BasketItems[i].Product.Price }; } //standard api call to recieve response var paymentType = new paymentType { Item = creditCard }; var transactionRequest = new transactionRequestType { transactionType = transactionTypeEnum.authCaptureTransaction.ToString(), amount = cvm.Order.TotalPrice, payment = paymentType, billTo = billingAddress, lineItems = MakeLineItems }; var request = new createTransactionRequest { transactionRequest = transactionRequest }; // instantiate new controller that will call service var controller = new createTransactionController(request); controller.Execute(); //get response from service (errors contained if any) var response = controller.GetApiResponse(); //validate response if (response.messages.resultCode == messageTypeEnum.Ok) { if (response.transactionResponse != null) { Console.WriteLine($"Success, Auth Code : {response.transactionResponse.authCode}"); } } else { Console.WriteLine($"Error : {response.messages.message[0].code} {response.messages.message[0].text}"); if (response.transactionResponse != null) { Console.WriteLine($"Transaction Error : {response.transactionResponse.errors[0].errorCode} {response.transactionResponse.errors[0].errorText}"); } } return(response); }
//public static ANetApiResponse Run(String ApiLoginID, String ApiTransactionKey, string customerProfileId) //{ // Console.WriteLine("CreateCustomerPaymentProfile Sample"); // ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = AuthorizeNET.Environment.SANDBOX; // ApiOperationBase<ANetApiRequest, ANetApiResponse>.MerchantAuthentication = new merchantAuthenticationType() // { // name = ApiLoginID, // ItemElementName = ItemChoiceType.transactionKey, // Item = ApiTransactionKey, // }; // var bankAccount = new bankAccountType // { // accountNumber = "01245524321", // routingNumber = "000000204", // accountType = bankAccountTypeEnum.checking, // echeckType = echeckTypeEnum.WEB, // nameOnAccount = "test", // bankName = "Bank Of America" // }; // paymentType echeck = new paymentType {Item = bankAccount}; // var billTo = new customerAddressType // { // firstName = "John", // lastName = "Snow" // }; // customerPaymentProfileType echeckPaymentProfile = new customerPaymentProfileType(); // echeckPaymentProfile.payment = echeck; // echeckPaymentProfile.billTo = billTo; // var request = new createCustomerPaymentProfileRequest // { // customerProfileId = customerProfileId, // paymentProfile = echeckPaymentProfile, // validationMode = validationModeEnum.none // }; // //Prepare Request // var controller = new createCustomerPaymentProfileController(request); // controller.Execute(); // //Send Request to EndPoint // createCustomerPaymentProfileResponse response = controller.GetApiResponse(); // if (response != null && response.messages.resultCode == messageTypeEnum.Ok) // { // if (response != null && response.messages.message != null) // { // Console.WriteLine("Success, createCustomerPaymentProfileID : " + response.customerPaymentProfileId); // } // } // else // { // Console.WriteLine("Error: " + response.messages.message[0].code + " " + response.messages.message[0].text); // if (response.messages.message[0].code == "E00039") // { // Console.WriteLine("Duplicate ID: " + response.customerPaymentProfileId); // } // } // return response; //} public static void CreateCustomerPaymentProfileExec(String ApiLoginID, String ApiTransactionKey) { using (CsvReader csv = new CsvReader(new StreamReader(new FileStream(@"../../../CSV_DATA/CreateCustomerPaymentProfile.csv", FileMode.Open)), true)) { Console.WriteLine("CreateCustomerPaymentProfile Sample"); int flag = 0; int fieldCount = csv.FieldCount; string[] headers = csv.GetFieldHeaders(); //Append Data var item1 = DataAppend.ReadPrevData(); using (CsvFileWriter writer = new CsvFileWriter(new FileStream(@"../../../CSV_DATA/Outputfile.csv", FileMode.Open))) { while (csv.ReadNextRecord()) { ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment = AuthorizeNET.Environment.SANDBOX; ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = new merchantAuthenticationType() { name = ApiLoginID, ItemElementName = ItemChoiceType.transactionKey, Item = ApiTransactionKey, }; var bankAccount = new bankAccountType { accountNumber = "01245524321", routingNumber = "000000204", accountType = bankAccountTypeEnum.checking, echeckType = echeckTypeEnum.WEB, nameOnAccount = "test", bankName = "Bank Of America" }; paymentType echeck = new paymentType { Item = bankAccount }; var billTo = new customerAddressType { firstName = "John", lastName = "Snow" }; customerPaymentProfileType echeckPaymentProfile = new customerPaymentProfileType(); echeckPaymentProfile.payment = echeck; echeckPaymentProfile.billTo = billTo; string customerProfileId = null; string TestCaseId = null; for (int i = 0; i < fieldCount; i++) { switch (headers[i]) { case "TestCaseId": TestCaseId = csv[i]; break; case "customerProfileId": customerProfileId = csv[i]; break; default: break; } } CsvRow row = new CsvRow(); try { if (flag == 0) { row.Add("TestCaseId"); row.Add("APIName"); row.Add("Status"); row.Add("TimeStamp"); writer.WriteRow(row); flag = flag + 1; //Append Data foreach (var item in item1) { writer.WriteRow(item); } } var request = new createCustomerPaymentProfileRequest { customerProfileId = customerProfileId, paymentProfile = echeckPaymentProfile, validationMode = validationModeEnum.none }; //Prepare Request var controller = new createCustomerPaymentProfileController(request); controller.Execute(); //Send Request to EndPoint createCustomerPaymentProfileResponse response = controller.GetApiResponse(); //var response = controller.GetApiResponse(); if (response != null && response.messages.resultCode == messageTypeEnum.Ok && response.messages.message != null) { /*****************************/ try { //Assert.AreEqual(response.Id, customerProfileId); //Console.WriteLine("Assertion Succeed! Valid customerProfileId fetched."); CsvRow row1 = new CsvRow(); row1.Add("CCPP_00" + flag.ToString()); row1.Add("CreateCustomerPaymentProfile"); row1.Add("Pass"); row1.Add(DateTime.Now.ToString("yyyy/MM/dd" + "::" + "HH:mm:ss:fff")); writer.WriteRow(row1); // Console.WriteLine("Success " + TestcaseID + " CustomerID : " + response.Id); flag = flag + 1; Console.WriteLine("Success, createCustomerPaymentProfileID : " + response.customerPaymentProfileId); } catch { CsvRow row1 = new CsvRow(); row1.Add("CCPP_00" + flag.ToString()); row1.Add("CreateCustomerPaymentProfile"); row1.Add("Fail"); row1.Add(DateTime.Now.ToString("yyyy/MM/dd" + "::" + "HH:mm:ss:fff")); writer.WriteRow(row1); Console.WriteLine("Assertion Failed! Invalid CustomerPaymentProfile fetched."); flag = flag + 1; } /*******************/ //if (response.messages.message != null) //{ // Console.WriteLine("Success, createCustomerPaymentProfileID : " + response.customerPaymentProfileId); //} } else { //Console.WriteLine("Error: " + response.messages.message[0].code + " " + response.messages.message[0].text); CsvRow row1 = new CsvRow(); row1.Add("CCPP_00" + flag.ToString()); row1.Add("CreateCustomerPaymentProfile"); row1.Add("Fail"); row1.Add(DateTime.Now.ToString("yyyy/MM/dd" + "::" + "HH:mm:ss:fff")); writer.WriteRow(row1); //Console.WriteLine("Assertion Failed! Invalid CustomerPaymentProfile fetched."); flag = flag + 1; //if (response.messages.message[0].code == "E00039") //{ // Console.WriteLine("Duplicate ID: " + response.customerPaymentProfileId); //} } //return response; } catch (Exception e) { CsvRow row2 = new CsvRow(); row2.Add("CCPP_00" + flag.ToString()); row2.Add("CreateCustomerPaymentProfile"); row2.Add("Fail"); row2.Add(DateTime.Now.ToString("yyyy/MM/dd" + "::" + "HH:mm:ss:fff")); writer.WriteRow(row2); flag = flag + 1; Console.WriteLine(TestCaseId + " Error Message " + e.Message); } } } } }
/// <summary> /// OnPost - Upon posting to this page (user checkout) a number of actions take place. This method constructs all of the pieces necessary for the most important operation: the purchase. This method assembles all of the final details needed to make the purchase including the user's shopping cart, to total price of all of the items in the cart, the billing/order address, and the credit card being used. Then finally a call is made to the payment service, the card gets ran, and the order is placed. The user inputs their billing information into a form, selects from one of the three seeded credit cards and then makes their purchase. /// </summary> /// <param name="firstName">Billing First Name</param> /// <param name="lastName">Billing Last Name</param> /// <param name="address">Billing Address</param> /// <param name="city">Billing City</param> /// <param name="state">Billing State</param> /// <param name="zip">Billing ZIP</param> /// <param name="cardNumber">Credit Card</param> /// <returns>The task complete, a successful (or unsuccessful) transaction has taken place.</returns> public async Task <IActionResult> OnPost(string firstName, string lastName, string address, string city, string state, int zip) { Cart cart = await _cart.GetCartForUserByEmail(GetUserEmail()); if (cart == null) { await _cart.Create(GetUserEmail()); } decimal totalPrice = 0; foreach (var item in cart.CartItems) { totalPrice += item.Product.Price * item.Quantity; } cart.Total = totalPrice; Total = totalPrice; var user = await _signInManager.UserManager.GetUserAsync(User); customerAddressType billingAddress = new customerAddressType() { firstName = firstName, lastName = lastName, email = user.UserName, address = address, city = city, state = state, zip = zip.ToString() }; creditCardType creditCard = new creditCardType() { cardNumber = _config[$"{CardType}TestNumber"], expirationDate = _config["ExpDate"], cardCode = _config["CVV"] }; CurrentCartId = cart.Id; CurrentUserCart = cart; var paymentResult = _payment.Run(creditCard, billingAddress, cart); if (paymentResult.Successful) { // GET CART ITEMS HERE List <CartItems> cartItems = await _cartItems.GetAllCartItems(CurrentCartId); Order newOrder = new Order() { CartId = cart.Id, UserEmail = user.Email, FirstName = firstName, LastName = lastName, Address = address, City = city, State = state, Zip = zip, Total = cart.Total }; Order order = await _order.Create(newOrder); order.Date = DateTime.UtcNow; StringBuilder sb = new StringBuilder(); foreach (var item in cart.CartItems) { sb.Append($"<li>{item.Product.Name} (Quantity: {item.Quantity})</li>"); } ; string subject = "Your Order Summary"; string htmlMessage = $"<h1>Thank you for your purchase {user.FirstName}.</h1><p>Your summary: {sb.ToString()}</p><p>Total purchase cost: ${totalPrice}</p><p>Your order is now being processed and should be heading your way soon. We hope you're happy with your purchase!</p>"; await _emailSender.SendEmailAsync(user.UserName, subject, htmlMessage); cart.IsActive = false; await _cart.Update(cart); await _cart.Create(GetUserEmail()); return(RedirectToPage("Receipt")); } return(Page()); }
public static void Run(string apiLoginId, string apiTransactionKey) { Console.WriteLine("CreateCustomerProfile Sample"); ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment = AuthorizeNet.Environment.SANDBOX; ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = new merchantAuthenticationType() { name = apiLoginId, ItemElementName = ItemChoiceType.transactionKey, Item = apiTransactionKey, }; var creditCard = new creditCardType { cardNumber = "4111111111111111", expirationDate = "0718" }; var bankAccount = new bankAccountType { accountNumber = "0123454321", routingNumber = "000000204", accountType = bankAccountTypeEnum.checking, echeckType = echeckTypeEnum.WEB, nameOnAccount = "test", bankName = "Bank Of America" }; //standard api call to retrieve response paymentType cc = new paymentType { Item = creditCard }; paymentType echeck = new paymentType { Item = bankAccount }; List <customerPaymentProfileType> paymentProfileList = new List <customerPaymentProfileType>(); customerPaymentProfileType ccPaymentProfile = new customerPaymentProfileType(); ccPaymentProfile.payment = cc; customerPaymentProfileType echeckPaymentProfile = new customerPaymentProfileType(); echeckPaymentProfile.payment = echeck; paymentProfileList.Add(ccPaymentProfile); paymentProfileList.Add(echeckPaymentProfile); List <customerAddressType> addressInfoList = new List <customerAddressType>(); customerAddressType homeAddress = new customerAddressType(); homeAddress.address = "10900 NE 8th St"; homeAddress.city = "Seattle"; homeAddress.zip = "98006"; customerAddressType officeAddress = new customerAddressType(); officeAddress.address = "1200 148th AVE NE"; officeAddress.city = "NorthBend"; officeAddress.zip = "92101"; addressInfoList.Add(homeAddress); addressInfoList.Add(officeAddress); customerProfileType customerProfile = new customerProfileType(); customerProfile.merchantCustomerId = "Test CustomerID"; customerProfile.email = "*****@*****.**"; customerProfile.paymentProfiles = paymentProfileList.ToArray(); customerProfile.shipToList = addressInfoList.ToArray(); var request = new createCustomerProfileRequest { profile = customerProfile, validationMode = validationModeEnum.none }; var controller = new createCustomerProfileController(request); // instantiate the contoller that will call the service controller.Execute(); createCustomerProfileResponse response = controller.GetApiResponse(); // get the response from the service (errors contained if any) //validate if (response != null && response.messages.resultCode == messageTypeEnum.Ok) { if (response.messages.message != null) { Console.WriteLine("Success, CustomerProfileID : " + response.customerProfileId); Console.WriteLine("Success, CustomerPaymentProfileID : " + response.customerPaymentProfileIdList[0]); Console.WriteLine("Success, CustomerShippingProfileID : " + response.customerShippingAddressIdList[0]); } } else { if (response != null) { Console.WriteLine("Error: " + response.messages.message[0].code + " " + response.messages.message[0].text); } } }
public ANetApiResponse Run(String ApiLoginID, String ApiTransactionKey, decimal amount) { Console.WriteLine("Charge Credit Card Sample"); //ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = AuthorizeNet.Environment.SANDBOX; ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment = AuthorizeNet.Environment.PRODUCTION; // define the merchant information (authentication / transaction id) ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = new merchantAuthenticationType() { name = ApiLoginID, ItemElementName = ItemChoiceType.transactionKey, Item = ApiTransactionKey, }; var creditCard = new creditCardType { cardNumber = TxtCardNo.Text.Trim(), expirationDate = GetExpiration().Trim(), cardCode = TxtSecNo.Text.Trim() }; var billingAddress = new customerAddressType { firstName = TxtFirstName.Text, lastName = TxtLastName.Text, address = TxtFrstAdd.Text, city = TxtCity.Text, zip = TxtZip.Text }; //standard api call to retrieve response var paymentType = new paymentType { Item = creditCard }; // Add line Items var lineItems = new lineItemType[1]; /*lineItems[0] = new lineItemType { itemId = "1", name = "t-shirt", quantity = 2, unitPrice = new Decimal(15.00), }; * lineItems[1] = new lineItemType { itemId = "2", name = "snowboard", quantity = 1, unitPrice = new Decimal(450.00) };*/ lineItems[0] = new lineItemType { itemId = "1", name = "subscription", quantity = 1, unitPrice = amount, description = Ddlyear.SelectedItem.Text }; var transactionRequest = new transactionRequestType { transactionType = transactionTypeEnum.authCaptureTransaction.ToString(), // charge the card amount = amount, payment = paymentType, billTo = billingAddress, lineItems = lineItems }; var request = new createTransactionRequest { transactionRequest = transactionRequest }; // instantiate the controller that will call the service var controller = new createTransactionController(request); controller.Execute(); // get the response from the service (errors contained if any) var response = controller.GetApiResponse(); // validate response if (response != null) { if (response.messages.resultCode == messageTypeEnum.Ok) { if (response.transactionResponse.messages != null) { Console.WriteLine("Successfully created transaction with Transaction ID: " + response.transactionResponse.transId); Console.WriteLine("Response Code: " + response.transactionResponse.responseCode); Console.WriteLine("Message Code: " + response.transactionResponse.messages[0].code); Console.WriteLine("Description: " + response.transactionResponse.messages[0].description); Console.WriteLine("Success, Auth Code : " + response.transactionResponse.authCode); paymentStatus = "success"; } else { Console.WriteLine("Failed Transaction."); if (response.transactionResponse.errors != null) { Console.WriteLine("Error Code: " + response.transactionResponse.errors[0].errorCode); Console.WriteLine("Error message: " + response.transactionResponse.errors[0].errorText); } paymentStatus = "failed"; } } else { Console.WriteLine("Failed Transaction."); if (response.transactionResponse != null && response.transactionResponse.errors != null) { Console.WriteLine("Error Code: " + response.transactionResponse.errors[0].errorCode); Console.WriteLine("Error message: " + response.transactionResponse.errors[0].errorText); } else { Console.WriteLine("Error Code: " + response.messages.message[0].code); Console.WriteLine("Error message: " + response.messages.message[0].text); } paymentStatus = "failed"; } } else { paymentStatus = "failed"; } return(response); }
public static void customerAddressType(customerAddressType request) { }
public static ANetApiResponse Run(String ApiLoginID, String ApiTransactionKey, string customerProfileId) { Console.WriteLine("CreateCustomerPaymentProfile Sample"); ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment = AuthorizeNET.Environment.SANDBOX; ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = new merchantAuthenticationType() { name = ApiLoginID, ItemElementName = ItemChoiceType.transactionKey, Item = ApiTransactionKey, }; var bankAccount = new bankAccountType { accountNumber = "01245524321", routingNumber = "000000204", accountType = bankAccountTypeEnum.checking, echeckType = echeckTypeEnum.WEB, nameOnAccount = "test", bankName = "Bank Of America" }; paymentType echeck = new paymentType { Item = bankAccount }; var billTo = new customerAddressType { firstName = "John", lastName = "Snow" }; customerPaymentProfileType echeckPaymentProfile = new customerPaymentProfileType(); echeckPaymentProfile.payment = echeck; echeckPaymentProfile.billTo = billTo; var request = new createCustomerPaymentProfileRequest { customerProfileId = customerProfileId, paymentProfile = echeckPaymentProfile, validationMode = validationModeEnum.none }; //Prepare Request var controller = new createCustomerPaymentProfileController(request); controller.Execute(); //Send Request to EndPoint createCustomerPaymentProfileResponse response = controller.GetApiResponse(); if (response != null && response.messages.resultCode == messageTypeEnum.Ok) { if (response != null && response.messages.message != null) { Console.WriteLine("Success, createCustomerPaymentProfileID : " + response.customerPaymentProfileId); } } else { Console.WriteLine("Error: " + response.messages.message[0].code + " " + response.messages.message[0].text); if (response.messages.message[0].code == "E00039") { Console.WriteLine("Duplicate ID: " + response.customerPaymentProfileId); } } return(response); }
public static ANetApiResponse Run( creditCardType creditCard, customerAddressType billingAddress, List <lineItemType> lineItems, decimal amount) { ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment = AuthorizeNet.Environment.SANDBOX; ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = new merchantAuthenticationType() { name = "4r3yN5eZ7F", ItemElementName = ItemChoiceType.transactionKey, Item = "5Q226P5BjUw97nSN", }; /* * * var creditCard = new creditCardType * { * cardNumber = "4111111111111115", * expirationDate = "1028", * cardCode = "123" * }; * * var billingAddress = new customerAddressType * { * firstName = "John", * lastName = "Doe", * address = "123 My St", * city = "OurTown", * zip = "98004" * }; */ //standard api call to retrieve response var paymentType = new paymentType { Item = creditCard }; // Add line Items //var lineItems = new lineItemType[2]; //lineItems[0] = new lineItemType { itemId = "1", name = "t-shirt", quantity = 2, unitPrice = new Decimal(15.00) }; //lineItems[1] = new lineItemType { itemId = "2", name = "snowboard", quantity = 1, unitPrice = new Decimal(450.00) }; var transactionRequest = new transactionRequestType { transactionType = transactionTypeEnum.authCaptureTransaction.ToString(), amount = amount, payment = paymentType, billTo = billingAddress, lineItems = lineItems.ToArray() }; var request = new createTransactionRequest { transactionRequest = transactionRequest }; var controller = new createTransactionController(request); controller.Execute(); var response = controller.GetApiResponse(); return(response); }
/// <summary> /// gets address and amount to charge and runs through the trasaction process /// </summary> /// <param name="cardNumber"></param> /// <param name="User"></param> /// <param name="cart"></param> /// <returns>String</returns> public string Run(string cardNumber, ApplicationUser user, Cart cart) { //sets the enviornment to sanbox ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment = AuthorizeNet.Environment.SANDBOX; //Gets access requirment from user secrets ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = new merchantAuthenticationType() { name = _configuration["AuthNetAPILogin"], ItemElementName = ItemChoiceType.transactionKey, Item = _configuration["AuthNetTransactionKey"] }; //gets credit card info var creditCard = new creditCardType { cardNumber = cardNumber, expirationDate = "1022" }; //gets the address customerAddressType billingAddress = GetAddress(user); //sets the payment type to credit card var paymentType = new paymentType { Item = creditCard }; var transactionRequest = new transactionRequestType { transactionType = transactionTypeEnum.authCaptureTransaction.ToString(), amount = cart.GrandTotal, payment = paymentType, billTo = billingAddress, }; //creates the request for the transaction createTransactionRequest request = new createTransactionRequest { transactionRequest = transactionRequest }; //creates the transaction controller var controller = new createTransactionController(request); controller.Execute(); var response = controller.GetApiResponse(); if (response != null) { if (response.messages.resultCode == messageTypeEnum.Ok) { if (response.transactionResponse.messages != null) { return("Okay"); } } else { return("Something Went Wrong"); } } return("Something Went Wrong"); }
public TransactionResponse ChargeCredit(PaymentModel payment) { // determine run Environment to SANDBOX for developemnt level ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment = AuthorizeNet.Environment.SANDBOX; // define the merchant information (authentication / transaction id) ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = new merchantAuthenticationType() { name = apiLoginId, ItemElementName = ItemChoiceType.transactionKey, Item = transactionKey, }; var creditCard = new creditCardType { cardNumber = payment.CardNumber, //"Ex: x111111111111111", expirationDate = payment.Month + payment.Year, //"Ex: 0522" cardCode = payment.CardCode, //"Ex: 111" }; var billingAddress = new customerAddressType { firstName = payment.FirstName, lastName = payment.LastName, city = payment.Address1, address = payment.Address2, zip = payment.Postcode, phoneNumber = payment.Phone }; //standard api call to retrieve response var paymentType = new paymentType { Item = creditCard }; // Add line Items you pay to obtain these var lineItems = new lineItemType[2]; lineItems[0] = new lineItemType { itemId = "1", name = "t-shirt", quantity = 2, unitPrice = new Decimal(1.00) }; lineItems[1] = new lineItemType { itemId = "2", name = "snowboard", quantity = 1, unitPrice = new Decimal(1.00) }; var transactionRequest = new transactionRequestType { transactionType = transactionTypeEnum.authCaptureTransaction.ToString(), // charge the card amount = 2, payment = paymentType, billTo = billingAddress, lineItems = lineItems }; var request = new createTransactionRequest { transactionRequest = transactionRequest }; // instantiate the contoller that will call the service var controller = new createTransactionController(request); controller.Execute(); var resCode = controller.GetResultCode(); var resAll = controller.GetResults(); // get the response from the service (errors contained if any) var response = controller.GetApiResponse(); //validate TransactionResponse result = new TransactionResponse(); if (response != null) { result.resultCode = response.messages.resultCode; if (response.messages.resultCode == messageTypeEnum.Ok) { if (response.transactionResponse.messages != null) { result.transId = response.transactionResponse.transId; result.responseCode = response.transactionResponse.responseCode; result.messageCode = response.transactionResponse.messages[0].code; result.description = response.transactionResponse.messages[0].description; result.authCode = response.transactionResponse.authCode; } else { if (response.transactionResponse.errors != null) { result.errorCode = response.transactionResponse.errors[0].errorCode; result.errorText = response.transactionResponse.errors[0].errorText; } } } else { if (response.transactionResponse != null && response.transactionResponse.errors != null) { result.errorCode = response.transactionResponse.errors[0].errorCode; result.errorText = response.transactionResponse.errors[0].errorText; } else { result.errorCode = response.messages.message[0].code; result.errorText = response.messages.message[0].text; } } } else { result.errorCode = "NONE"; result.errorText = "Failed Transaction,, Unkown Error"; } return(result); }
public string Run(long creditCardPassInside, int experationCardIniside) { ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment = AuthorizeNet.Environment.SANDBOX; //define merchant information (authentication & transaction ID) ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = new merchantAuthenticationType() { name = _configuration["AuthNetAPILogin"], ItemElementName = ItemChoiceType.transactionKey, Item = _configuration["AuthNetTransactionKey"] }; //CREATE A CREDIT CARD we need a cc //bring in a parameter var creditCard = new creditCardType { //Drop down or have user put in their own CC and check that it's for the future cardNumber = creditCardPassInside.ToString(), expirationDate = experationCardIniside.ToString() }; customerAddressType billingAddress = new customerAddressType(); var paymentType = new paymentType { Item = creditCard }; //transaction request type consolidate all the info before sending to autho.net //1. amount of order transactionRequestType transactionRequest = new transactionRequestType { transactionType = transactionTypeEnum.authCaptureTransaction.ToString(), amount = 2.34m, payment = paymentType, billTo = billingAddress, //lineItems = lineItems, }; createTransactionRequest request = new createTransactionRequest { transactionRequest = transactionRequest }; //Make a call out to Autho.Net var controller = new createTransactionController(request); //execcute the callll controller.Execute(); //Response from call above var response = controller.GetApiResponse(); if (response != null) { if (response.messages.resultCode == messageTypeEnum.Ok) { if (response.transactionResponse != null) { //Console.WriteLine("Success, Auth Code : " + response.transactionResponse.authCode); return("OK"); } } else { Console.WriteLine("Transaction Error : " + response.transactionResponse.errors[0].errorCode + " " + response.transactionResponse.errors[0].errorText); return("This is NOT ok!"); } } return("Does not works"); /* * // validate response * if (response != null) * { * if (response.messages.resultCode == messageTypeEnum.Ok) * { * if (response.transactionResponse.messages != null) * { * Console.WriteLine("Successfully created transaction with Transaction ID: " + response.transactionResponse.transId); * Console.WriteLine("Response Code: " + response.transactionResponse.responseCode); * Console.WriteLine("Message Code: " + response.transactionResponse.messages[0].code); * Console.WriteLine("Description: " + response.transactionResponse.messages[0].description); * Console.WriteLine("Success, Auth Code : " + response.transactionResponse.authCode); * } * else * { * Console.WriteLine("Failed Transaction."); * if (response.transactionResponse.errors != null) * { * Console.WriteLine("Error Code: " + response.transactionResponse.errors[0].errorCode); * Console.WriteLine("Error message: " + response.transactionResponse.errors[0].errorText); * } * } * } * else * { * Console.WriteLine("Failed Transaction."); * if (response.transactionResponse != null && response.transactionResponse.errors != null) * { * Console.WriteLine("Error Code: " + response.transactionResponse.errors[0].errorCode); * Console.WriteLine("Error message: " + response.transactionResponse.errors[0].errorText); * } * else * { * Console.WriteLine("Error Code: " + response.messages.message[0].code); * Console.WriteLine("Error message: " + response.messages.message[0].text); * } * } * } * else * { * Console.WriteLine("Null Response."); * } * * return "It was submitted. That's all I can say";*/ }
public string Run() { // controllers.Base for authoriseNet ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment = AuthorizeNet.Environment.SANDBOX; ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = new merchantAuthenticationType() { name = _config["AN-ApiLoginID"], ItemElementName = ItemChoiceType.transactionKey, Item = _config["AN-TransactionKey"] }; // set a credit card. // can be hard coded. or brought in through secrets // DO NOT ask the user for their credit number var creditCard = new creditCardType { cardNumber = "4111111111111111", expirationDate = "1020", cardCode = "102" }; customerAddressType billingAddress = GetAddress("someUserId"); var paymentType = new paymentType { Item = creditCard }; // this class takes everything we've defined, and puts it all in one object. var potato = new transactionRequestType { transactionType = transactionTypeEnum.authCaptureTransaction.ToString(), amount = 122.5m, payment = paymentType, billTo = billingAddress }; var request = new createTransactionRequest { transactionRequest = potato }; var controller = new createTransactionController(request); // This is going to produce an error! // to fix this error........ // PM> install-package System.Configuration.ConfigurationManager controller.Execute(); var response = controller.GetApiResponse(); if (response != null) { if (response.messages.resultCode == messageTypeEnum.Ok) { return("success!"); } } return("fail"); }
public static String Run(String AccessToken, String CardNumber, DateTime ExpirationDate, decimal Amount) { Console.WriteLine("Charge Credit Card Sample"); ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment = AuthorizeNet.Environment.SANDBOX; // define the merchant information (authentication / transaction id) ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = new merchantAuthenticationType() { ItemElementName = ItemChoiceType.accessToken, Item = AccessToken, }; var creditCard = new creditCardType { cardNumber = CardNumber, expirationDate = ExpirationDate.ToString("MMyy"), cardCode = "123" }; var billingAddress = new customerAddressType { firstName = "John", lastName = "Doe", address = "123 My St", city = "OurTown", zip = "99091" }; //standard api call to retrieve response var paymentType = new paymentType { Item = creditCard }; // Add line Items var lineItems = new lineItemType[2]; lineItems[0] = new lineItemType { itemId = "1", name = "t-shirt", quantity = 2, unitPrice = new Decimal(15.00) }; lineItems[1] = new lineItemType { itemId = "2", name = "snowboard", quantity = 1, unitPrice = new Decimal(450.00) }; var transactionRequest = new transactionRequestType { transactionType = transactionTypeEnum.authCaptureTransaction.ToString(), // charge the card amount = Amount, payment = paymentType, billTo = billingAddress, lineItems = lineItems }; var request = new createTransactionRequest { transactionRequest = transactionRequest }; // instantiate the contoller that will call the service var controller = new createTransactionController(request); controller.Execute(); // get the response from the service (errors contained if any) var response = controller.GetApiResponse(); //validate StringBuilder toReturn = new StringBuilder(); if (response != null) { if (response.messages.resultCode == messageTypeEnum.Ok) { if (response.transactionResponse.messages != null) { toReturn.AppendLine("Successfully created transaction with Transaction ID: " + response.transactionResponse.transId); toReturn.AppendLine("Response Code: " + response.transactionResponse.responseCode); toReturn.AppendLine("Message Code: " + response.transactionResponse.messages[0].code); toReturn.AppendLine("Description: " + response.transactionResponse.messages[0].description); toReturn.AppendLine("Success, Auth Code : " + response.transactionResponse.authCode); } else { toReturn.AppendLine("Failed Transaction."); if (response.transactionResponse.errors != null) { toReturn.AppendLine("Error Code: " + response.transactionResponse.errors[0].errorCode); toReturn.AppendLine("Error message: " + response.transactionResponse.errors[0].errorText); } } } else { toReturn.AppendLine("Failed Transaction."); if (response.transactionResponse != null && response.transactionResponse.errors != null) { toReturn.AppendLine("Error Code: " + response.transactionResponse.errors[0].errorCode); toReturn.AppendLine("Error message: " + response.transactionResponse.errors[0].errorText); } else { toReturn.AppendLine("Error Code: " + response.messages.message[0].code); toReturn.AppendLine("Error message: " + response.messages.message[0].text); } } } else { toReturn.AppendLine("Null Response."); } return(toReturn.ToString()); }
public static ANetApiResponse Run(String ApiLoginID, String ApiTransactionKey, decimal amount) { Console.WriteLine("Create an Accept Payment Transaction Sample"); ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment = AuthorizeNet.Environment.SANDBOX; // define the merchant information (authentication / transaction id) ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = new merchantAuthenticationType() { name = ApiLoginID, ItemElementName = ItemChoiceType.transactionKey, Item = ApiTransactionKey, }; var opaqueData = new opaqueDataType { dataDescriptor = "COMMON.ACCEPT.INAPP.PAYMENT", dataValue = "119eyJjb2RlIjoiNTBfMl8wNjAwMDUyN0JEODE4RjQxOUEyRjhGQkIxMkY0MzdGQjAxQUIwRTY2NjhFNEFCN0VENzE4NTUwMjlGRUU0M0JFMENERUIwQzM2M0ExOUEwMDAzNzlGRDNFMjBCODJEMDFCQjkyNEJDIiwidG9rZW4iOiI5NDkwMjMyMTAyOTQwOTk5NDA0NjAzIiwidiI6IjEuMSJ9" }; var billingAddress = new customerAddressType { firstName = "John", lastName = "Doe", address = "123 My St", city = "OurTown", zip = "98004" }; //standard api call to retrieve response var paymentType = new paymentType { Item = opaqueData }; // Add line Items var lineItems = new lineItemType[2]; lineItems[0] = new lineItemType { itemId = "1", name = "t-shirt", quantity = 2, unitPrice = new Decimal(15.00) }; lineItems[1] = new lineItemType { itemId = "2", name = "snowboard", quantity = 1, unitPrice = new Decimal(450.00) }; var transactionRequest = new transactionRequestType { transactionType = transactionTypeEnum.authCaptureTransaction.ToString(), // charge the card amount = amount, payment = paymentType, billTo = billingAddress, lineItems = lineItems }; var request = new createTransactionRequest { transactionRequest = transactionRequest }; // instantiate the contoller that will call the service var controller = new createTransactionController(request); controller.Execute(); // get the response from the service (errors contained if any) var response = controller.GetApiResponse(); //validate if (response != null) { if (response.messages.resultCode == messageTypeEnum.Ok) { if (response.transactionResponse.messages != null) { Console.WriteLine("Successfully created transaction with Transaction ID: " + response.transactionResponse.transId); Console.WriteLine("Response Code: " + response.transactionResponse.responseCode); Console.WriteLine("Message Code: " + response.transactionResponse.messages[0].code); Console.WriteLine("Description: " + response.transactionResponse.messages[0].description); Console.WriteLine("Success, Auth Code : " + response.transactionResponse.authCode); } else { Console.WriteLine("Failed Transaction."); if (response.transactionResponse.errors != null) { Console.WriteLine("Error Code: " + response.transactionResponse.errors[0].errorCode); Console.WriteLine("Error message: " + response.transactionResponse.errors[0].errorText); } } } else { Console.WriteLine("Failed Transaction."); if (response.transactionResponse != null && response.transactionResponse.errors != null) { Console.WriteLine("Error Code: " + response.transactionResponse.errors[0].errorCode); Console.WriteLine("Error message: " + response.transactionResponse.errors[0].errorText); } else { Console.WriteLine("Error Code: " + response.messages.message[0].code); Console.WriteLine("Error message: " + response.messages.message[0].text); } } } else { Console.WriteLine("Null Response."); } return(response); }
public static AuthorizeNetResponse ExecutePayment(Order newOrder, creditCardType creditCardInfo) { ConfigureAuthorizeNetAPI(); AuthorizeNetResponse authorizeNetResponse = new AuthorizeNetResponse(); try { var billingAddress = new customerAddressType { firstName = newOrder.CustomerName, email = newOrder.CustomerEmail, phoneNumber = newOrder.CustomerPhone, country = newOrder.CustomerCountry, city = newOrder.CustomerCity, address = newOrder.CustomerAddress, zip = newOrder.CustomerZipCode }; //standard api call to retrieve response var paymentType = new paymentType { Item = creditCardInfo }; var lineItems = new lineItemType[newOrder.OrderItems.Count]; var i = 0; foreach (var orderItem in newOrder.OrderItems) { lineItems[i] = new lineItemType { itemId = orderItem.ProductID.ToString(), name = orderItem.ProductName.ToAuthorizeNetProductName(), quantity = orderItem.Quantity, unitPrice = orderItem.ItemPrice }; i++; } var transactionRequest = new transactionRequestType { transactionType = transactionTypeEnum.authCaptureTransaction.ToString(), // charge the card amount = newOrder.FinalAmmount, payment = paymentType, billTo = billingAddress, shipTo = billingAddress, lineItems = lineItems, }; var request = new createTransactionRequest { transactionRequest = transactionRequest }; // instantiate the controller that will call the service var controller = new createTransactionController(request); controller.Execute(); // get the response from the service (errors contained if any) authorizeNetResponse.Response = controller.GetApiResponse(); // validate response if (authorizeNetResponse.Response != null) { if (authorizeNetResponse.Response.messages.resultCode == messageTypeEnum.Ok) { if (authorizeNetResponse.Response.transactionResponse.messages != null) { authorizeNetResponse.Success = true; authorizeNetResponse.Message = string.Format("Transaction Successfull.{0}Transaction ID is {1}", Environment.NewLine, authorizeNetResponse.Response.transactionResponse.transId); authorizeNetResponse.Response = authorizeNetResponse.Response; } else { authorizeNetResponse.Success = false; authorizeNetResponse.Message = string.Format("Transaction Failed.{0}{1}", Environment.NewLine, string.Join(Environment.NewLine, authorizeNetResponse.Response.transactionResponse.errors.Select(x => string.Format("Error: {0}~{1}", x.errorCode, x.errorText)).ToList())); authorizeNetResponse.Response = authorizeNetResponse.Response; } } else { authorizeNetResponse.Success = false; if (authorizeNetResponse.Response.transactionResponse != null && authorizeNetResponse.Response.transactionResponse.errors != null) { authorizeNetResponse.Message = string.Format("Transaction Failed.{0}{1}", Environment.NewLine, string.Join(Environment.NewLine, authorizeNetResponse.Response.transactionResponse.errors.Select(x => string.Format("Error: {0}~{1}", x.errorCode, x.errorText)).ToList())); } else { authorizeNetResponse.Message = string.Format("Transaction Failed.{0}{1}", Environment.NewLine, string.Join(Environment.NewLine, authorizeNetResponse.Response.messages.message.Select(x => string.Format("Error: {0}~{1}", x.code, x.text)).ToList())); } authorizeNetResponse.Response = authorizeNetResponse.Response; } } else { authorizeNetResponse.Success = false; authorizeNetResponse.Message = "No valid response from Authorize.Net."; authorizeNetResponse.Response = authorizeNetResponse.Response; } } catch { authorizeNetResponse.Success = false; authorizeNetResponse.Message = string.Format("Error occured on server."); } return(authorizeNetResponse); }
/// <summary> /// Submitting the whats in the cart and sending it to the user /// </summary> /// <returns>Sending the email</returns> public async Task <IActionResult> OnPost() { /// Checking to see if user had filled out right information if (ModelState.IsValid) { // Computing total price await GetData(); //validating the address using the USPS api string response = ValidateAddress(); // if the return XML contains error, then it will output error message and have user fill out again if (response.Contains("Error")) { ModelState.AddModelError(String.Empty, "Please Enter Correct Address"); return(Page()); } int orderNumber = _orderManager.OrderNumberGenerator(); /// this is to track what order user has placed and store that in the database foreach (var item in CartItems) { OrderList orderList = new OrderList { FirstName = Userinfo.FirstName, LastName = Userinfo.LastName, OrderDate = DateTime.Now, TotalPrice = TotalPrice, ProductID = item.ProductID, Quantities = item.Quantity, CartsID = item.CartsID, OrderNumber = orderNumber }; await _orderManager.CreateOrder(orderList); } /// Using the view models to create an object of customerAddressType to send it through PaymentService customerAddressType addressInfo = new customerAddressType { firstName = Userinfo.FirstName, lastName = Userinfo.LastName, address = Userinfo.ShippingAddress, city = Userinfo.City, zip = Userinfo.ZipCode.ToString() }; // As the result of Authorize.net payment process, it will return false, if it didn't go through, and it will return true if it did. bool result = _payment.Run(addressInfo, TotalPrice); // Only routing them back if the payment have processed correctly. if (result) { // redirect them to receipt page once the payment goes through return(RedirectToPage("Receipt", Userinfo)); } } // otherwise, it will reroute them to page return(Page()); }
public void CreateTransactionFromProfile() { //Creates a customer profile and customer payment profile //Then uses those profiles to create a transaction request //Common code to set for all requests ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = CustomMerchantAuthenticationType; ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment = TestEnvironment; Random rnd = new Random(DateTime.Now.Millisecond); string profileRandom = rnd.Next(9999).ToString(); //Create profile to use in transaction creation var profileShipTo = new customerAddressType { address = profileRandom + " First St NE", city = "Bellevue", state = "WA", zip = "98007", company = "Sample Co " + profileRandom, country = "USA", firstName = "Sample" + profileRandom, lastName = "Name" + profileRandom, phoneNumber = "425 123 4567", }; var paymentProfile = new customerPaymentProfileType { billTo = profileShipTo, customerType = customerTypeEnum.individual, payment = new paymentType { Item = new creditCardType { cardNumber = "4111111111111111", expirationDate = "0622" } }, }; var createProfileReq = new createCustomerProfileRequest { profile = new customerProfileType { description = "SampleProfile " + profileRandom, email = "SampleEmail" + profileRandom + "@Visa.com", shipToList = new customerAddressType[] { profileShipTo }, paymentProfiles = new customerPaymentProfileType[] { paymentProfile } } }; var createProfileCont = new createCustomerProfileController(createProfileReq); createProfileCont.Execute(); var createProfileResp = createProfileCont.GetApiResponse(); //Get profile using getCustomerProfileRequest var getCustReq = new getCustomerProfileRequest { customerProfileId = createProfileResp.customerProfileId }; var getCustCont = new getCustomerProfileController(getCustReq); getCustCont.Execute(); var getCustResp = getCustCont.GetApiResponse(); //Create Transaction //Create instance of customer payment profile using the profile IDs from the profile we loaded above. var custPaymentProfile = new AuthorizeNet.Api.Contracts.V1.customerProfilePaymentType { customerProfileId = getCustResp.profile.customerProfileId, paymentProfile = new paymentProfile { paymentProfileId = getCustResp.profile.paymentProfiles[0].customerPaymentProfileId } }; var testTxn = new transactionRequestType { profile = custPaymentProfile, amount = (decimal)rnd.Next(9999) / 100, transactionType = transactionTypeEnum.authCaptureTransaction.ToString() }; var txnControler = new createTransactionController(new createTransactionRequest { transactionRequest = testTxn }); txnControler.Execute(); var txnControlerResp = txnControler.GetApiResponse(); //verify transaction succeeded. Assert.AreEqual("1", txnControlerResp.transactionResponse.messages[0].code); }
public static Array PostPay(string AuthorizeLoginID, string AuthorizeTransactionKey, FetchResponse bookingDetails, PaymentViewModel payDetails, decimal AmountToBeCharged = 0) { string env = System.Configuration.ConfigurationManager.AppSettings["enviroment"].ToString(); if (env == "production") { ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment = AuthorizeNet.Environment.PRODUCTION; } else { ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment = AuthorizeNet.Environment.SANDBOX; } // define the merchant information (authentication / transaction id) ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = new merchantAuthenticationType() { name = AuthorizeLoginID, ItemElementName = ItemChoiceType.transactionKey, Item = AuthorizeTransactionKey, }; var orderType = new orderType { invoiceNumber = bookingDetails.lbkg.ToString(), description = "PreCheckIn payment", }; var customerData = new customerDataType { type = customerTypeEnum.individual, email = bookingDetails.guest.emai }; var creditCard = new creditCardType { cardNumber = payDetails.cardNumber.Replace(" ", ""), // bookingDetails.stay.card.numb.Replace(" ",""), expirationDate = payDetails.cardEndDate.Replace(" ", ""), // bookingDetails.stay.card.expy.Replace("/", ""), cardCode = payDetails.cardCode // bookingDetails.stay.card.auth }; var billingAddress = new customerAddressType { firstName = bookingDetails.guest.namf, lastName = bookingDetails.guest.naml, email = bookingDetails.guest.emai, address = bookingDetails.guest.addr.line1, city = bookingDetails.guest.addr.city, state = bookingDetails.guest.addr.stat, country = bookingDetails.guest.addr.cnty, company = bookingDetails.guest.comp, phoneNumber = bookingDetails.guest.phon, zip = bookingDetails.guest.addr.posc }; var retailType = new transRetailInfoType { marketType = "2", deviceType = "8" }; //standard api call to retrieve response var paymentType = new paymentType { Item = creditCard }; // Add line Items var lineItems = new lineItemType[1]; lineItems[0] = new lineItemType { itemId = "1", name = "PreCheckIn of booking " + bookingDetails.lbkg.ToString(), quantity = 1, unitPrice = bookingDetails.stay.fcst, totalAmount = AmountToBeCharged }; var transactionRequest = new transactionRequestType { transactionType = transactionTypeEnum.authCaptureTransaction.ToString(),// charge the card refTransId = bookingDetails.lbkg.ToString(), order = orderType, customer = customerData, lineItems = lineItems, payment = paymentType, amount = AmountToBeCharged, billTo = billingAddress, }; var request = new createTransactionRequest { transactionRequest = transactionRequest }; // instantiate the controller that will call the service var controller = new createTransactionController(request); controller.Execute(); // get the response from the service (errors contained if any) var response = controller.GetApiResponse(); Array response_array = new string[6]; // validate response if (response != null) { if (response.messages.resultCode == messageTypeEnum.Ok) { if (response.transactionResponse.messages != null) { response_array.SetValue(response.transactionResponse.responseCode, 0); //Response Code response_array.SetValue(response.transactionResponse.messages[0].code, 1); //Message Code response_array.SetValue(response.transactionResponse.messages[0].description, 2); //Description response_array.SetValue(response.transactionResponse.authCode, 3); //Success, Auth Code response_array.SetValue(response.transactionResponse.transId, 4); //Transaction ID response_array.SetValue(bookingDetails.lbkg.ToString(), 5); //Reference ID Console.WriteLine("Successfully created transaction with Transaction ID: " + response.transactionResponse.transId); Console.WriteLine("Response Code: " + response.transactionResponse.responseCode); Console.WriteLine("Message Code: " + response.transactionResponse.messages[0].code); Console.WriteLine("Description: " + response.transactionResponse.messages[0].description); Console.WriteLine("Success, Auth Code : " + response.transactionResponse.authCode); } else { //Failed Transaction. if (response.transactionResponse.errors != null) { response_array.SetValue("2", 0); //Response Code response_array.SetValue(response.transactionResponse.errors[0].errorCode, 1); //Message Code response_array.SetValue(response.transactionResponse.errors[0].errorText, 2); //Description response_array.SetValue(response.transactionResponse.authCode, 3); //Success, Auth Code response_array.SetValue(response.transactionResponse.transId, 4); //Transaction ID response_array.SetValue(bookingDetails.lbkg.ToString(), 5); //Reference ID Console.WriteLine("Error Code: " + response.transactionResponse.errors[0].errorCode); Console.WriteLine("Error message: " + response.transactionResponse.errors[0].errorText); } } } else { //Failed Transaction. if (response.transactionResponse != null && response.transactionResponse.errors != null) { response_array.SetValue("2", 0); //Response Code response_array.SetValue(response.transactionResponse.errors[0].errorCode, 1); //Message Code response_array.SetValue(response.transactionResponse.errors[0].errorText, 2); //Description response_array.SetValue(response.transactionResponse.authCode, 3); //Success, Auth Code response_array.SetValue(response.transactionResponse.transId, 4); //Transaction ID response_array.SetValue(bookingDetails.lbkg.ToString(), 5); //Reference ID Console.WriteLine("Error Code: " + response.transactionResponse.errors[0].errorCode); Console.WriteLine("Error message: " + response.transactionResponse.errors[0].errorText); } else { response_array.SetValue("3", 0); //Response Code response_array.SetValue(response.messages.message[0].code, 1); //Message Code response_array.SetValue(response.messages.message[0].text, 2); //Description response_array.SetValue(response.transactionResponse.authCode, 3); //Success, Auth Code response_array.SetValue(response.transactionResponse.transId, 4); //Transaction ID response_array.SetValue(bookingDetails.lbkg.ToString(), 5); //Reference ID Console.WriteLine("Error Code: " + response.messages.message[0].code); Console.WriteLine("Error message: " + response.messages.message[0].text); } } } else { Console.WriteLine("Null Response."); response_array.SetValue("-1", 0); response_array.SetValue(bookingDetails.lbkg.ToString(), 5); //Reference ID } //return response; return(response_array); }
/// <summary> /// Run - Method that is used to process a user's payment information. /// </summary> /// <param name="creditCard">The user's credit card used for the purchase.</param> /// <param name="billingAddress">The user's billing address.</param> /// <param name="cart">The cart the user is attempting to process.</param> /// <returns>Transaction response, detailing whether the purchase was successful or denied.</returns> public TransactionResponse Run(creditCardType creditCard, customerAddressType billingAddress, Cart cart) { ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment = AuthorizeNet.Environment.SANDBOX; ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = new merchantAuthenticationType() { name = _config["AuthorizeLoginId"], ItemElementName = ItemChoiceType.transactionKey, Item = _config["AuthorizeTransactionKey"] }; var paymentType = new paymentType { Item = creditCard }; decimal total = 0; lineItemType[] lineItems = new lineItemType[cart.CartItems.Count]; for (int i = 0; i < lineItems.Length; i++) { var cartItem = cart.CartItems[i]; total += cartItem.Product.Price * cartItem.Quantity; lineItems[i] = new lineItemType { itemId = cartItem.ProductId.ToString(), name = cartItem.Product.Name, quantity = cartItem.Quantity, unitPrice = cartItem.Product.Price }; } var transRequest = new transactionRequestType { transactionType = transactionTypeEnum.authCaptureTransaction.ToString(), amount = total, payment = paymentType, billTo = billingAddress, lineItems = lineItems }; var request = new createTransactionRequest { transactionRequest = transRequest }; var controller = new createTransactionController(request); controller.Execute(); var response = controller.GetApiResponse(); if (response != null) { if (response.transactionResponse != null) { return(new TransactionResponse { Successful = true, Response = $"Transaction Success: {response.transactionResponse.authCode}" }); } else if (response.transactionResponse == null) { return(new TransactionResponse { Successful = false, Response = $"Transaction Error: {response.transactionResponse.errors[0].errorCode} {response.transactionResponse.errors[0].errorText}" }); } } return(new TransactionResponse { Successful = false, Response = "" }); }
public async Task <IActionResult> OnPost() { string EmailInput = Request.Form["Email"]; string Address = Request.Form["Address"]; string FirstName = Request.Form["FirstName"]; string LastName = Request.Form["LastName"]; string City = Request.Form["City"]; string State = Request.Form["State"]; string Zip = Request.Form["Zip"]; DateTime Time = DateTime.Now; ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment = AuthorizeNet.Environment.SANDBOX; ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = new merchantAuthenticationType() { name = _config["ApiLoginID"], ItemElementName = ItemChoiceType.transactionKey, Item = _config["TransactionKey"] }; ApplicationUser user = await _userManager.GetUserAsync(User); CartItems = await _cart.GetAllCartItems(user.Id); decimal total = 0; foreach (var item in CartItems) { decimal price = item.Quantity * item.Product.Price; total += price; } total += 32; Order order = new Order() { FirstName = FirstName, LastName = LastName, UserID = EmailInput, Address = Address, City = City, Zip = Zip, State = State, TotalPrice = total, Time = DateTime.Now.ToString() }; await _order.AddNewOrder(order); IList <OrderDetails> OrderDetails = new List <OrderDetails>(); foreach (var item in CartItems) { OrderDetails orderDetail = new OrderDetails() { OrderID = order.ID, ProductID = item.Product.ID, Quantity = item.Quantity }; OrderDetails.Add(orderDetail); } foreach (var item in OrderDetails) { await _order.AddOrderItem(item); } var creditCard = new creditCardType { cardNumber = "4111111111111111", expirationDate = "1022", cardCode = "777" }; customerAddressType address = new customerAddressType { firstName = FirstName, lastName = LastName, address = Address, city = City, zip = Zip, state = State, email = EmailInput, }; var paymentType = new paymentType { Item = creditCard }; var transaction = new transactionRequestType { transactionType = transactionTypeEnum.authCaptureTransaction.ToString(), amount = total, payment = paymentType, billTo = address }; var request = new createTransactionRequest { transactionRequest = transaction }; var controller = new createTransactionController(request); controller.Execute(); var response = controller.GetApiResponse(); if (response != null) { if (response.messages.resultCode == messageTypeEnum.Ok) { StringBuilder sb = new StringBuilder(); sb.AppendLine("<h1> Thank You for your order!</h1>"); sb.AppendLine("<p> This is a list of items purchased </p>"); foreach (var item in CartItems) { sb.AppendLine($"<p>{item.Product.Name} Quantity: {item.Quantity}. </p>"); } sb.AppendLine("<p> Hope to see you again soon! </p>"); await _email.SendEmailAsync($"{user.Email}", "The Seattle Pour - Your orders have been submitted!", sb.ToString()); await _cart.RemoveAllCartItems(CartItems); return(RedirectToAction("Receipt", "Store")); } } await _cart.RemoveAllCartItems(CartItems); return(RedirectToAction("Receipt", "Store")); }