public void MockARBCreateSubscriptionTest() { //define all mocked objects as final var mockController = GetMockController <ARBCreateSubscriptionRequest, ARBCreateSubscriptionResponse>(); var mockRequest = new ARBCreateSubscriptionRequest { merchantAuthentication = new merchantAuthenticationType { name = "mocktest", Item = "mockKey", ItemElementName = ItemChoiceType.transactionKey }, subscription = ArbSubscriptionOne, }; var mockResponse = new ARBCreateSubscriptionResponse { refId = "1234", sessionToken = "sessiontoken", subscriptionId = "1234", }; var errorResponse = new ANetApiResponse(); var results = new List <String>(); const messageTypeEnum messageTypeOk = messageTypeEnum.Ok; SetMockControllerExpectations <ARBCreateSubscriptionRequest, ARBCreateSubscriptionResponse, ARBCreateSubscriptionController>( mockController.MockObject, mockRequest, mockResponse, errorResponse, results, messageTypeOk); mockController.MockObject.Execute(AuthorizeNet.Environment.CUSTOM); //mockController.MockObject.Execute(); // or var controllerResponse = mockController.MockObject.ExecuteWithApiResponse(AuthorizeNet.Environment.CUSTOM); var controllerResponse = mockController.MockObject.GetApiResponse(); Assert.IsNotNull(controllerResponse); Assert.IsNotNull(controllerResponse.subscriptionId); LogHelper.info(Logger, "ARBCreateSubscription: Details:{0}", controllerResponse.subscriptionId); }
public static ANetApiResponse Run(String ApiLoginID, String ApiTransactionKey, short intervalLength, string customerProfileId, string customerPaymentProfileId, string customerAddressId) { Console.WriteLine("Create Subscription Sample"); ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment = AuthorizeNet.Environment.SANDBOX; ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = new merchantAuthenticationType() { name = ApiLoginID, ItemElementName = ItemChoiceType.transactionKey, Item = ApiTransactionKey }; paymentScheduleTypeInterval interval = new paymentScheduleTypeInterval(); interval.length = intervalLength; // months can be indicated between 1 and 12 interval.unit = ARBSubscriptionUnitEnum.days; paymentScheduleType schedule = new paymentScheduleType { interval = interval, startDate = DateTime.Now.AddDays(1), // start date should be tomorrow totalOccurrences = 9999, // 999 indicates no end date trialOccurrences = 3 }; #region Payment Information var creditCard = new creditCardType { cardNumber = "4111111111111111", expirationDate = "0718" }; //standard api call to retrieve response paymentType cc = new paymentType { Item = creditCard }; #endregion customerProfileIdType customerProfile = new customerProfileIdType() { customerProfileId = customerProfileId, customerPaymentProfileId = customerPaymentProfileId, customerAddressId = customerAddressId }; ARBSubscriptionType subscriptionType = new ARBSubscriptionType() { amount = 35.55m, trialAmount = 0.00m, paymentSchedule = schedule, profile = customerProfile }; var request = new ARBCreateSubscriptionRequest { subscription = subscriptionType }; var controller = new ARBCreateSubscriptionController(request); // instantiate the controller that will call the service controller.Execute(); ARBCreateSubscriptionResponse response = controller.GetApiResponse(); // get the response from the service (errors contained if any) // validate response if (response != null && response.messages.resultCode == messageTypeEnum.Ok) { if (response != null && response.messages.message != null) { Console.WriteLine("Success, Subscription ID : " + response.subscriptionId.ToString()); } } else if (response != null) { Console.WriteLine("Error: " + response.messages.message[0].code + " " + response.messages.message[0].text); } return(response); }
//public static ANetApiResponse Run(String ApiLoginID, String ApiTransactionKey, short intervalLength, // string customerProfileId, string customerPaymentProfileId, string customerAddressId) //{ // Console.WriteLine("Create Subscription Sample"); // ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = AuthorizeNET.Environment.SANDBOX; // ApiOperationBase<ANetApiRequest, ANetApiResponse>.MerchantAuthentication = new merchantAuthenticationType() // { // name = ApiLoginID, // ItemElementName = ItemChoiceType.transactionKey, // Item = ApiTransactionKey // }; // paymentScheduleTypeInterval interval = new paymentScheduleTypeInterval(); // interval.length = intervalLength; // months can be indicated between 1 and 12 // interval.unit = ARBSubscriptionUnitEnum.days; // paymentScheduleType schedule = new paymentScheduleType // { // interval = interval, // startDate = DateTime.Now.AddDays(1), // start date should be tomorrow // totalOccurrences = 9999, // 999 indicates no end date // trialOccurrences = 3 // }; // #region Payment Information // var creditCard = new creditCardType // { // cardNumber = "4111111111111111", // expirationDate = "0718" // }; // //standard api call to retrieve response // paymentType cc = new paymentType { Item = creditCard }; // #endregion // customerProfileIdType customerProfile = new customerProfileIdType() // { // customerProfileId = customerProfileId, // customerPaymentProfileId = customerPaymentProfileId, // customerAddressId = customerAddressId // }; // ARBSubscriptionType subscriptionType = new ARBSubscriptionType() // { // amount = 35.55m, // trialAmount = 0.00m, // paymentSchedule = schedule, // profile = customerProfile // }; // var request = new ARBCreateSubscriptionRequest {subscription = subscriptionType }; // var controller = new ARBCreateSubscriptionController(request); // instantiate the contoller that will call the service // controller.Execute(); // ARBCreateSubscriptionResponse response = controller.GetApiResponse(); // get the response from the service (errors contained if any) // //validate // if (response != null && response.messages.resultCode == messageTypeEnum.Ok) // { // if (response != null && response.messages.message != null) // { // Console.WriteLine("Success, Subscription ID : " + response.subscriptionId.ToString()); // } // } // else if(response != null) // { // Console.WriteLine("Error: " + response.messages.message[0].code + " " + response.messages.message[0].text); // } // return response; //} public static void CreateSubscriptionFromCustomerProfileExec(String ApiLoginID, String ApiTransactionKey) { using (CsvReader csv = new CsvReader(new StreamReader(new FileStream(@"../../../CSV_DATA/CreateASubscriptionFromCustomerProfile.csv", FileMode.Open)), true)) { Console.WriteLine("Create Subscription 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()) { // Create Instance of Customer Api 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, }; string customerProfileId = null; string TestCase_Id = null; string length = null; string customerPaymentProfileId = null; string customerAddressId = null; for (int i = 0; i < fieldCount; i++) { switch (headers[i]) { case "customerProfileId": customerProfileId = csv[i]; break; case "customerPaymentProfileId": customerPaymentProfileId = csv[i]; break; case "customerAddressId": customerAddressId = csv[i]; break; case "length": length = csv[i]; break; case "TestCase_Id": TestCase_Id = csv[i]; break; default: break; } } //Write to output file 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); } } paymentScheduleTypeInterval interval = new paymentScheduleTypeInterval(); interval.length = Convert.ToInt16(length); // months can be indicated between 1 and 12 interval.unit = ARBSubscriptionUnitEnum.days; paymentScheduleType schedule = new paymentScheduleType { interval = interval, startDate = DateTime.Now.AddDays(1), // start date should be tomorrow totalOccurrences = 9999, // 999 indicates no end date trialOccurrences = 3 }; #region Payment Information var creditCard = new creditCardType { cardNumber = "4111111111111111", expirationDate = "0718" }; //standard api call to retrieve response paymentType cc = new paymentType { Item = creditCard }; #endregion customerProfileIdType customerProfile = new customerProfileIdType() { customerProfileId = customerProfileId, customerPaymentProfileId = customerPaymentProfileId, customerAddressId = customerAddressId }; ARBSubscriptionType subscriptionType = new ARBSubscriptionType() { amount = 35.55m, trialAmount = 0.00m, paymentSchedule = schedule, profile = customerProfile }; var request = new ARBCreateSubscriptionRequest { subscription = subscriptionType }; var controller = new ARBCreateSubscriptionController(request); // instantiate the contoller that will call the service controller.Execute(); ARBCreateSubscriptionResponse 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 CustomerId fetched."); CsvRow row1 = new CsvRow(); row1.Add("CASFCP_00" + flag.ToString()); row1.Add("CreateSubscriptionFromCustomerProfile"); 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, Subscription ID : " + response.subscriptionId.ToString()); } catch { CsvRow row1 = new CsvRow(); row1.Add("CASFCP_00" + flag.ToString()); row1.Add("CreateSubscriptionFromCustomerProfile"); row1.Add("Assertion Failed!"); row1.Add(DateTime.Now.ToString("yyyy/MM/dd" + "::" + "HH:mm:ss:fff")); writer.WriteRow(row1); Console.WriteLine("Assertion Failed! Invalid CustomerId fetched."); flag = flag + 1; } } else { CsvRow row1 = new CsvRow(); row1.Add("CASFCP_00" + flag.ToString()); row1.Add("CreateSubscriptionFromCustomerProfile"); row1.Add("Fail"); row1.Add(DateTime.Now.ToString("yyyy/MM/dd" + "::" + "HH:mm:ss:fff")); writer.WriteRow(row1); //Console.WriteLine("Assertion Failed! Invalid CustomerId fetched."); flag = flag + 1; } } catch (Exception e) { CsvRow row2 = new CsvRow(); row2.Add("CASFCP_00" + flag.ToString()); row2.Add("CreateSubscriptionFromCustomerProfile"); row2.Add("Fail"); row2.Add(DateTime.Now.ToString("yyyy/MM/dd" + "::" + "HH:mm:ss:fff")); writer.WriteRow(row2); flag = flag + 1; Console.WriteLine(TestCase_Id + " Error Message " + e.Message); } } } } }
/// <summary> /// Processes the payment. /// </summary> /// <param name="payment">The payment.</param> /// <param name="message">The message.</param> /// <returns></returns> public override bool ProcessPayment(Payment payment, ref string message) { string erroneousConfigurationMessage = "Authorize.NET payment gateway is not configured correctly. {0} is not set."; // cast the object first CreditCardPayment info = (CreditCardPayment)payment; if (info == null) { message = "Payment information is not specified."; throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "", message); } // Check if the gateway is configured correctly string processUrl = String.Empty; string user = String.Empty; string password = String.Empty; string recurringMethod = String.Empty; string cancelStatus = String.Empty; #region Getting parameters from the db // get user name if (!Settings.ContainsKey(_UserParameterName) || String.IsNullOrEmpty(Settings[_UserParameterName])) { message = String.Format(erroneousConfigurationMessage, _UserParameterName); throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "", message); } user = Settings[_UserParameterName]; // get transaction key if (!Settings.ContainsKey(_TransactionKeyParameterName) || String.IsNullOrEmpty(Settings[_TransactionKeyParameterName])) { message = String.Format(erroneousConfigurationMessage, _TransactionKeyParameterName); throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "", message); } password = Settings[_TransactionKeyParameterName]; #endregion bool processRegularTransaction = true; #region --------------- Process Transaction --------------- if (payment.Parent != null && (payment.Parent.Parent is PaymentPlan)) { // get recurring method and determine which type of transaction to perform if (!Settings.ContainsKey(_RecurringMethodParameterName) || String.IsNullOrEmpty(Settings[_RecurringMethodParameterName])) { message = String.Format(erroneousConfigurationMessage, _RecurringMethodParameterName); throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "", message); } recurringMethod = Settings[_RecurringMethodParameterName]; if (String.Compare(recurringMethod, _AuthorizeRecurringMethodParameterValue, StringComparison.OrdinalIgnoreCase) == 0) { processRegularTransaction = false; } } if (processRegularTransaction) { #region Get parameters for the regular transaction // get processing url if (!Settings.ContainsKey(_ProcessUrlParameterName) || String.IsNullOrEmpty(Settings[_ProcessUrlParameterName])) { message = String.Format(erroneousConfigurationMessage, _ProcessUrlParameterName); throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "", message); } processUrl = Settings[_ProcessUrlParameterName]; #endregion #region Process regular transaction AuthorizeNetManager mgr = new AuthorizeNetManager(processUrl, user, password); TransactionData transData = new TransactionData(); transData.card = new CreditCard(); transData.type = Settings[_PaymentOptionParameterName] == "S" ? TransactionType.Sale : TransactionType.Authorization; transData.totalAmount = (double)GetSumInUSD(info.Amount, info.Parent.Parent.BillingCurrency); transData.card.cardNr = info.CreditCardNumber; transData.card.CSC = info.CreditCardSecurityCode; transData.card.expDate = new DateTime(info.ExpirationYear, info.ExpirationMonth, 1); // Find the address OrderAddress address = null; foreach (OrderAddress a in info.Parent.Parent.OrderAddresses) { if (a.Name == info.BillingAddressId) { address = a; break; } } if (address == null) { throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "", "Billing address was not specified."); } transData.card.customerAddress = new Authorize.Address(); transData.card.customerAddress.countryCode = address.CountryCode; transData.card.customerAddress.zipCode = address.PostalCode; transData.card.customerAddress.city = address.City; transData.card.customerAddress.state = address.State; transData.card.customerAddress.street = address.Line1; transData.card.customerFirstName = address.FirstName; transData.card.customerLastName = address.LastName; transData.card.customerFax = address.FaxNumber; transData.card.customerPhone = address.DaytimePhoneNumber; transData.card.customerEMail = address.Email; ResponsePackage pkg = null; try { pkg = mgr.PerformCardTransaction(transData); } catch (PaymentException ex) { throw; //message = ex.Message; //return false; } catch { throw new PaymentException(PaymentException.ErrorType.ConnectionFailed, "", "Failed to connect to the payment gateway."); } //info.TextResponse = pkg.responseReasonText; info.AuthorizationCode = pkg.responseCode; info.ValidationCode = pkg.approvalCode; #endregion } else { #region Get parameters for the recurring transaction // get processing url if (!Settings.ContainsKey(_RecurringProcessUrlParameterName) || String.IsNullOrEmpty(Settings[_RecurringProcessUrlParameterName])) { message = String.Format(erroneousConfigurationMessage, _RecurringProcessUrlParameterName); throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "", message); } processUrl = Settings[_RecurringProcessUrlParameterName]; // get cancel status if (!Settings.ContainsKey(_CancelStatusParameterName) || String.IsNullOrEmpty(Settings[_CancelStatusParameterName])) { message = String.Format(erroneousConfigurationMessage, _CancelStatusParameterName); throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "", message); } cancelStatus = Settings[_CancelStatusParameterName]; #endregion PaymentPlan plan = (PaymentPlan)payment.Parent.Parent; #region Process recurring Authorize.NET transaction // Payment Plan -> Recurring transaction AuthorizeNetRecurringManager recurringMgr = new AuthorizeNetRecurringManager(processUrl, user, password); ANetApiResponse response = null; try { if (String.Compare(plan.Status, cancelStatus, StringComparison.OrdinalIgnoreCase) == 0) { // cancel subscription if (!String.IsNullOrEmpty(payment.AuthorizationCode)) { ARBCancelSubscriptionResponse cancelResponse = recurringMgr.CancelSubscription(PopulateCancelSubscriptionRequest(info)); // clear the authorization code info.AuthorizationCode = String.Empty; } else { throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "Payment AuthorizationCode cannot be null for the CancelSubscription operation", message); } } else if (plan.CompletedCyclesCount == 0) { if (String.IsNullOrEmpty(info.AuthorizationCode)) { // create subscription ARBCreateSubscriptionResponse createResponse = recurringMgr.CreateSubscription(PopulateCreateSubscriptionRequest(info)); response = (ANetApiResponse)createResponse; info.AuthorizationCode = createResponse.subscriptionId; } else { // update subscription recurringMgr.UpdateSubscription(PopulateUpdateSubscriptionRequest(info)); } } else { message = "The operation is invalid."; } } catch (PaymentException ex) { throw ex; } catch { throw new PaymentException(PaymentException.ErrorType.ConnectionFailed, "", "Failed to connect to the payment gateway."); } #endregion } #endregion return(true); }
public void CreateSub(SubscriptionModel cCnumber) { ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment = AuthorizeNet.Environment.SANDBOX; ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = new merchantAuthenticationType() { name = ApiLoginID, ItemElementName = ItemChoiceType.transactionKey, Item = ApiTransactionKey, }; paymentScheduleTypeInterval interval = new paymentScheduleTypeInterval(); interval.length = cCnumber.subscriptionLength; // months can be indicated between 1 and 12 interval.unit = ARBSubscriptionUnitEnum.months; paymentScheduleType schedule = new paymentScheduleType { interval = interval, startDate = DateTime.Now.AddDays(1), // start date should be tomorrow totalOccurrences = 9999, // 999 indicates no end date trialOccurrences = 3 }; #region Payment Information var creditCard = new creditCardType { cardNumber = cCnumber.CardNumber, expirationDate = cCnumber.Expiration }; //standard api call to retrieve response paymentType cc = new paymentType { Item = creditCard }; #endregion nameAndAddressType addressInfo = new nameAndAddressType() { firstName = cCnumber.FirstNameOnCard, lastName = cCnumber.LastNameOnCard }; ARBSubscriptionType subscriptionType = new ARBSubscriptionType() { amount = 35.55m, trialAmount = 0.00m, paymentSchedule = schedule, billTo = addressInfo, payment = cc }; var request = new ARBCreateSubscriptionRequest { subscription = subscriptionType }; var controller = new ARBCreateSubscriptionController(request); // instantiate the contoller that will call the service controller.Execute(); ARBCreateSubscriptionResponse response = controller.GetApiResponse(); // get the response from the service (errors contained if any) SubId = response.subscriptionId.ToString(); //validate if (response != null && response.messages.resultCode == messageTypeEnum.Ok) { if (response != null && response.messages.message != null) { Debug.WriteLine("Success, Create Subscription ID : " + response.subscriptionId.ToString()); } } else { Debug.WriteLine("Error: subscription" + response.messages.message[0].code + " " + response.messages.message[0].text); } }
public static string CreateSubscription(string firstName, string lastName, string email, string cardNumber, string expiration, decimal price, DateTime startDate) { ARBCreateSubscriptionRequest createSubscriptionRequest = new ARBCreateSubscriptionRequest(); ARBSubscriptionType subscription = new ARBSubscriptionType(); creditCardType creditCard = new creditCardType(); subscription.name = "Referral NetworX"; creditCard.cardNumber = cardNumber; creditCard.expirationDate = expiration; subscription.payment = new paymentType(); subscription.payment.Item = creditCard; subscription.billTo = new nameAndAddressType { firstName = firstName, lastName = lastName }; subscription.paymentSchedule = new paymentScheduleType { startDate = startDate, startDateSpecified = true, totalOccurrences = 9999, totalOccurrencesSpecified = true, trialOccurrencesSpecified = false, interval = new paymentScheduleTypeInterval { length = 1, unit = ARBSubscriptionUnitEnum.months } }; subscription.trialAmountSpecified = false; subscription.amount = price; subscription.amountSpecified = true; subscription.customer = new customerType { email = email }; ANetApiRequest aNetRequest = (ANetApiRequest)createSubscriptionRequest; aNetRequest.merchantAuthentication = new merchantAuthenticationType { name = "8n3jE77yAPK", transactionKey = "7C5v485g9vKJZ9mH" }; createSubscriptionRequest.subscription = subscription; ////////////////////// XmlSerializer serializer; XmlDocument xmldoc; HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://api.authorize.net/xml/v1/request.api"); webRequest.Method = "POST"; webRequest.ContentType = "text/xml"; webRequest.KeepAlive = true; serializer = new XmlSerializer(createSubscriptionRequest.GetType()); XmlWriter xmlwriter = new XmlTextWriter(webRequest.GetRequestStream(), Encoding.UTF8); serializer.Serialize(xmlwriter, createSubscriptionRequest); xmlwriter.Close(); WebResponse webResponse = webRequest.GetResponse(); xmldoc = new XmlDocument(); xmldoc.Load(XmlReader.Create(webResponse.GetResponseStream())); object apiResponse = null; switch (xmldoc.DocumentElement.Name) { case "ARBCreateSubscriptionResponse": serializer = new XmlSerializer(typeof(ARBCreateSubscriptionResponse)); apiResponse = (ARBCreateSubscriptionResponse)serializer.Deserialize(new StringReader(xmldoc.DocumentElement.OuterXml)); break; case "ARBUpdateSubscriptionResponse": serializer = new XmlSerializer(typeof(ARBUpdateSubscriptionResponse)); apiResponse = (ARBUpdateSubscriptionResponse)serializer.Deserialize(new StringReader(xmldoc.DocumentElement.OuterXml)); break; case "ARBCancelSubscriptionResponse": serializer = new XmlSerializer(typeof(ARBCancelSubscriptionResponse)); apiResponse = (ARBCancelSubscriptionResponse)serializer.Deserialize(new StringReader(xmldoc.DocumentElement.OuterXml)); break; case "ARBGetSubscriptionStatusResponse": serializer = new XmlSerializer(typeof(ARBGetSubscriptionStatusResponse)); apiResponse = (ARBGetSubscriptionStatusResponse)serializer.Deserialize(new StringReader(xmldoc.DocumentElement.OuterXml)); break; case "ErrorResponse": serializer = new XmlSerializer(typeof(ANetApiResponse)); apiResponse = (ANetApiResponse)serializer.Deserialize(new StringReader(xmldoc.DocumentElement.OuterXml)); break; } ANetApiResponse baseResponse = (ANetApiResponse)apiResponse; //display.InnerHtml = baseResponse.messages.resultCode.ToString() + "<br />"; string subscriptionId = null; if (baseResponse.messages.resultCode == messageTypeEnum.Ok) { if (apiResponse.GetType() == typeof(ARBCreateSubscriptionResponse)) { ARBCreateSubscriptionResponse createSubscriptionResponse = (ARBCreateSubscriptionResponse)apiResponse; subscriptionId = createSubscriptionResponse.subscriptionId; } } else { foreach (messagesTypeMessage message in baseResponse.messages.message) { subscriptionId += message.code + ": " + message.text + "<br />"; } } return(subscriptionId); }