public static void ARBCreateSubscriptionRequest(ARBCreateSubscriptionRequest request) { if (null != request) { ARBSubscriptionType(request.subscription); } }
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 void ARBGetSubscriptionSampleTest() { LogHelper.info(Logger, "Sample GetSubscriptionList"); ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = CustomMerchantAuthenticationType; ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment = TestEnvironment; //create a subscription var createRequest = new ARBCreateSubscriptionRequest { refId = RefId, subscription = ArbSubscriptionOne, }; var createController = new ARBCreateSubscriptionController(createRequest); createController.Execute(); var createResponse = createController.GetApiResponse(); Assert.IsNotNull(createResponse.subscriptionId); LogHelper.info(Logger, "Created Subscription: {0}", createResponse.subscriptionId); var subscriptionId = createResponse.subscriptionId; //get subscription details var getRequest = new ARBGetSubscriptionRequest { refId = RefId, subscriptionId = subscriptionId }; var getController = new ARBGetSubscriptionController(getRequest); var getResponse = getController.ExecuteWithApiResponse(); Assert.IsNotNull(getResponse.subscription); Logger.info(String.Format("Subscription Name : {0}", getResponse.subscription.name)); Assert.AreEqual(ArbSubscriptionOne.name, getResponse.subscription.name); Assert.AreEqual(ArbSubscriptionOne.amountSpecified, getResponse.subscription.amountSpecified); //cancel subscription var cancelRequest = new ARBCancelSubscriptionRequest { merchantAuthentication = CustomMerchantAuthenticationType, refId = RefId, subscriptionId = subscriptionId }; var cancelController = new ARBCancelSubscriptionController(cancelRequest); var cancelResponse = cancelController.ExecuteWithApiResponse(TestEnvironment); Assert.IsNotNull(cancelResponse.messages); Logger.info(String.Format("Subscription Cancelled: {0}", subscriptionId)); }
public void TestSubscription_serialization_error() { Random rnd = new Random(DateTime.Now.Millisecond); ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = CustomMerchantAuthenticationType; ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment = TestEnvironment; //create a subscription var subscriptionDef = new ARBSubscriptionType { paymentSchedule = new paymentScheduleType { interval = new paymentScheduleTypeInterval { length = 1, unit = ARBSubscriptionUnitEnum.months, }, startDate = DateTime.UtcNow, totalOccurrences = 12, }, amount = 9.99M, billTo = new customerAddressType { firstName = "first", lastName = "last" }, payment = PaymentOne, customer = CustomerOne, order = new orderType { description = string.Format("member monthly {0}", rnd.Next(99999)) }, }; var arbRequest = new ARBCreateSubscriptionRequest { subscription = subscriptionDef }; var arbController = new ARBCreateSubscriptionController(arbRequest); arbController.Execute(); if (arbController.GetResultCode() == messageTypeEnum.Error) { var errorResp = arbController.GetErrorResponse(); Console.WriteLine("{0}: {1}", errorResp.messages.message[0].code, errorResp.messages.message[0].text); } }
/// <summary> /// Create a new ARB Subscription. /// </summary> public ARBCreateSubscriptionResponse CreateSubscription(ARBCreateSubscriptionRequest createSubscriptionRequest) { // Populate the authentication information PopulateMerchantAuthentication((ANetApiRequest)createSubscriptionRequest); ValidateCreateSubscribtionParameters(createSubscriptionRequest); // The response type will normally be ARBCreateSubscriptionResponse. // However, in the case of an error such as an XML parsing error, the response // type will be ErrorResponse. object response = ProcessRequest(createSubscriptionRequest); // process response. If there are any errors, exception will be thrown. CheckResponseForErrors(response); return((ARBCreateSubscriptionResponse)response); }
public void TestSubscription() { Random rnd = new Random(DateTime.Now.Millisecond); ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = CustomMerchantAuthenticationType; ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment = TestEnvironment; //create a subscription var subscriptionDef = new ARBSubscriptionType { paymentSchedule = new paymentScheduleType { interval = new paymentScheduleTypeInterval { length = 1, unit = ARBSubscriptionUnitEnum.months, }, startDate = DateTime.UtcNow, totalOccurrences = 12, }, amount = 9.99M, billTo = new nameAndAddressType { firstName = "first", lastName = "last", address = "123 elm st ne", city = "Bellevue", state = "Wa", zip = "98007" }, payment = PaymentOne, customer = CustomerOne, order = new orderType { description = string.Format("member monthly {0}", rnd.Next(99999)) }, }; var arbRequest = new ARBCreateSubscriptionRequest { subscription = subscriptionDef }; var arbController = new ARBCreateSubscriptionController(arbRequest); arbController.Execute(); var arbCreateResponse = arbController.GetApiResponse(); Assert.AreEqual(messageTypeEnum.Ok, arbController.GetResultCode()); }
private ARBCreateSubscriptionController CreateSubscriptionRequestTest(ARBSubscriptionType subscriptionRequestParameter) { if (subscriptionRequestParameter == null) { throw new ArgumentNullException("subscriptionRequestParameter"); } LogHelper.info(Logger, "CreateSubscriptionRequestTest"); ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = CustomMerchantAuthenticationType; ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment = TestEnvironment; var arbRequest = new ARBCreateSubscriptionRequest { subscription = subscriptionRequestParameter }; var arbController = new ARBCreateSubscriptionController(arbRequest); return(arbController); }
private string CreateSubscription(merchantAuthenticationType merchantAuthentication) { //create a new subscription //RequestFactoryWithSpecified.paymentType(ArbSubscriptionOne.payment); //RequestFactoryWithSpecified.paymentScheduleType(ArbSubscriptionOne.paymentSchedule); //RequestFactoryWithSpecified.ARBSubscriptionType(ArbSubscriptionOne); var createRequest = new ARBCreateSubscriptionRequest { merchantAuthentication = merchantAuthentication, refId = RefId, subscription = ArbSubscriptionOne, }; var createResponse = ExecuteTestRequestWithSuccess <ARBCreateSubscriptionRequest, ARBCreateSubscriptionResponse, ARBCreateSubscriptionController>(createRequest, TestEnvironment); Assert.IsNotNull(createResponse.subscriptionId); LogHelper.info(Logger, "Created Subscription: {0}", createResponse.subscriptionId); return(createResponse.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 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); } } } } }
public async Task <ITransactionResponse> CreateSubscription(ICustomerPayment customerPayment) { var transactionResponse = new TransactionResponse(); var task = Task.Run(() => { if (Convert.ToBoolean(string.IsNullOrEmpty(ConfigurationManager.AppSettings["AuthNetIsProduction"]) ? "false" : ConfigurationManager.AppSettings["AuthNetIsProduction"])) { 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 = ApiLoginID, ItemElementName = ItemChoiceType.transactionKey, Item = ApiTransactionKey, }; paymentScheduleTypeInterval interval = new paymentScheduleTypeInterval(); interval.length = 1; // months can be indicated between 1 and 12 interval.unit = ARBSubscriptionUnitEnum.months; paymentScheduleType schedule = new paymentScheduleType { interval = interval, startDate = customerPayment.StartDate, // start date should be tomorrow totalOccurrences = customerPayment.TotalOccurrences, // 9999 indicates no end date trialOccurrences = customerPayment.TrialOccurrences }; var creditCard = new creditCardType { cardNumber = customerPayment.CardNumber, expirationDate = customerPayment.ExpirationDate, cardCode = customerPayment.CardCode }; var billingAddress = new nameAndAddressType { company = customerPayment.Company, firstName = customerPayment.FirstName, lastName = customerPayment.LastName, address = customerPayment.Address, city = customerPayment.City, zip = customerPayment.Zip }; //standard api call to retrieve response var paymentType = new paymentType { Item = creditCard }; ARBSubscriptionType subscriptionType = new ARBSubscriptionType() { amount = customerPayment.Amount, trialAmount = customerPayment.TrialAmount, paymentSchedule = schedule, billTo = billingAddress, payment = paymentType }; var request = new ARBCreateSubscriptionRequest { subscription = subscriptionType }; // instantiate the contoller that will call the service var controller = new ARBCreateSubscriptionController(request); controller.Execute(); // get the response from the service (errors contained if any) var response = controller.GetApiResponse(); if (response != null && response.messages.resultCode == messageTypeEnum.Ok) { if (response != null && response.messages.message != null) { System.Diagnostics.Debug.WriteLine("Success, Subscription ID : " + response.subscriptionId.ToString()); transactionResponse.Errors = null; transactionResponse.IsSuccess = true; transactionResponse.Messages = null; transactionResponse.RefTransID = response.refId; transactionResponse.SubscriptionId = response.subscriptionId; } else { transactionResponse.IsSuccess = false; } } else if (response != null && response.messages.message != null) { transactionResponse.IsSuccess = false; System.Diagnostics.Debug.WriteLine("Error: " + response.messages.message[0].code + " " + response.messages.message[0].text); transactionResponse.Messages = new TransactionResponseMessage[] { new TransactionResponseMessage() { Code = response.messages.message[0].code, Description = response.messages.message[0].text } }; } return(response); }); await task; return(transactionResponse); }
public void TestSubscription_ExpiredCC() { Random rnd = new Random(DateTime.Now.Millisecond); ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = CustomMerchantAuthenticationType; ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment = TestEnvironment; //create a subscription var subscriptionDef = new ARBSubscriptionType { paymentSchedule = new paymentScheduleType { interval = new paymentScheduleTypeInterval { length = 7, unit = ARBSubscriptionUnitEnum.days }, startDate = DateTime.UtcNow, totalOccurrences = 2, }, amount = 9.99M, billTo = new nameAndAddressType { address = "1234 Elm St NE", city = "Bellevue", state = "WA", zip = "98007", firstName = "First", lastName = "Last" }, payment = new paymentType { Item = new creditCardType { cardCode = "655", //cardNumber = "4007000", cardNumber = "4111111111111111", expirationDate = "122013", } }, customer = new customerType { email = "*****@*****.**", id = "5", }, order = new orderType { description = string.Format("member monthly {0}", rnd.Next(99999)) }, }; var arbRequest = new ARBCreateSubscriptionRequest { subscription = subscriptionDef }; var arbController = new ARBCreateSubscriptionController(arbRequest); arbController.Execute(); var arbCreateResponse = arbController.GetApiResponse(); //If request responds with an error, walk the messages and get code and text for each message. if (arbController.GetResultCode() == messageTypeEnum.Error) { foreach (var msg in arbCreateResponse.messages.message) { Console.WriteLine("Error Num = {0}, Message = {1}", msg.code, msg.text); } } }
/// <summary> /// Process recurring payment /// </summary> /// <param name="processPaymentRequest">Payment info required for an order processing</param> /// <returns>Process payment result</returns> public ProcessPaymentResult ProcessRecurringPayment(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 }; var billTo = new nameAndAddressType { firstName = customer.BillingAddress.FirstName, lastName = customer.BillingAddress.LastName, //email = customer.BillingAddress.Email, address = customer.BillingAddress.Address1, //address = customer.BillingAddress.Address1 + " " + customer.BillingAddress.Address2; 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 dtNow = DateTime.UtcNow; // Interval can't be updated once a subscription is created. var paymentScheduleInterval = new paymentScheduleTypeInterval(); switch (processPaymentRequest.RecurringCyclePeriod) { case RecurringProductCyclePeriod.Days: paymentScheduleInterval.length = Convert.ToInt16(processPaymentRequest.RecurringCycleLength); paymentScheduleInterval.unit = ARBSubscriptionUnitEnum.days; break; case RecurringProductCyclePeriod.Weeks: paymentScheduleInterval.length = Convert.ToInt16(processPaymentRequest.RecurringCycleLength * 7); paymentScheduleInterval.unit = ARBSubscriptionUnitEnum.days; break; case RecurringProductCyclePeriod.Months: paymentScheduleInterval.length = Convert.ToInt16(processPaymentRequest.RecurringCycleLength); paymentScheduleInterval.unit = ARBSubscriptionUnitEnum.months; break; case RecurringProductCyclePeriod.Years: paymentScheduleInterval.length = Convert.ToInt16(processPaymentRequest.RecurringCycleLength * 12); paymentScheduleInterval.unit = ARBSubscriptionUnitEnum.months; break; default: throw new NopException("Not supported cycle period"); } var paymentSchedule = new paymentScheduleType { startDate = new DateTime(dtNow.Year, dtNow.Month, dtNow.Day), totalOccurrences = Convert.ToInt16(processPaymentRequest.RecurringTotalCycles), interval = paymentScheduleInterval }; var subscriptionType = new ARBSubscriptionType { name = processPaymentRequest.OrderGuid.ToString(), amount = Math.Round(processPaymentRequest.OrderTotal, 2), payment = paymentType, billTo = billTo, paymentSchedule = paymentSchedule, customer = new customerType { email = customer.BillingAddress.Email //phone number should be in one of following formats: 111- 111-1111 or (111) 111-1111. //phoneNumber = customer.BillingAddress.PhoneNumber }, 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("Recurring payment #{0}", processPaymentRequest.OrderGuid) } }; if (customer.ShippingAddress != null) { var shipTo = new nameAndAddressType { firstName = customer.ShippingAddress.FirstName, lastName = customer.ShippingAddress.LastName, address = customer.ShippingAddress.Address1, city = customer.ShippingAddress.City, zip = customer.ShippingAddress.ZipPostalCode }; if (customer.ShippingAddress.StateProvince != null) { shipTo.state = customer.ShippingAddress.StateProvince.Abbreviation; } subscriptionType.shipTo = shipTo; } var request = new ARBCreateSubscriptionRequest { subscription = subscriptionType }; // instantiate the contoller that will call the service var controller = new ARBCreateSubscriptionController(request); controller.Execute(); // get the response from the service (errors contained if any) var response = controller.GetApiResponse(); //validate if (response != null && response.messages.resultCode == messageTypeEnum.Ok) { result.SubscriptionTransactionId = response.subscriptionId; result.AuthorizationTransactionCode = response.refId; result.AuthorizationTransactionResult = string.Format("Approved ({0}: {1})", response.refId, response.subscriptionId); } else if (response != null) { foreach (var responseMessage in response.messages.message) { result.AddError(string.Format("Error processing recurring payment #{0}: {1}", responseMessage.code, responseMessage.text)); } } else { result.AddError("Authorize.NET unknown error"); } return(result); }
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); }
/// <summary> /// Checks the length of strings in the request and corrects it when needed. /// </summary> /// <param name="request"></param> private void ValidateCreateSubscribtionParameters(ARBCreateSubscriptionRequest request) { if (request.subscription != null) { if (!String.IsNullOrEmpty(request.subscription.name) && request.subscription.name.Length > 50) { request.subscription.name = request.subscription.name.Substring(0, 50); } if (request.subscription.customer != null) { if (!String.IsNullOrEmpty(request.subscription.customer.id) && request.subscription.customer.id.Length > 20) { request.subscription.customer.id = request.subscription.customer.id.Substring(0, 20); } if (!String.IsNullOrEmpty(request.subscription.customer.email) && request.subscription.customer.email.Length > 255) { request.subscription.customer.email = request.subscription.customer.email.Substring(0, 255); } if (!String.IsNullOrEmpty(request.subscription.customer.phoneNumber) && request.subscription.customer.phoneNumber.Length > 25) { request.subscription.customer.phoneNumber = request.subscription.customer.phoneNumber.Substring(0, 25); } if (!String.IsNullOrEmpty(request.subscription.customer.faxNumber) && request.subscription.customer.faxNumber.Length > 25) { request.subscription.customer.faxNumber = request.subscription.customer.faxNumber.Substring(0, 25); } } if (request.subscription.order != null) { if (!String.IsNullOrEmpty(request.subscription.order.invoiceNumber) && request.subscription.order.invoiceNumber.Length > 20) { request.subscription.order.invoiceNumber = request.subscription.order.invoiceNumber.Substring(0, 20); } if (!String.IsNullOrEmpty(request.subscription.order.description) && request.subscription.order.description.Length > 255) { request.subscription.order.description = request.subscription.order.description.Substring(0, 255); } } if (request.subscription.billTo != null) { if (request.subscription.billTo.firstName.Length > 50) { request.subscription.billTo.firstName = request.subscription.billTo.firstName.Substring(0, 50); } if (request.subscription.billTo.lastName.Length > 50) { request.subscription.billTo.lastName = request.subscription.billTo.lastName.Substring(0, 50); } if (!String.IsNullOrEmpty(request.subscription.billTo.company) && request.subscription.billTo.company.Length > 50) { request.subscription.billTo.company = request.subscription.billTo.company.Substring(0, 50); } if (!String.IsNullOrEmpty(request.subscription.billTo.address) && request.subscription.billTo.address.Length > 60) { request.subscription.billTo.address = request.subscription.billTo.address.Substring(0, 60); } if (!String.IsNullOrEmpty(request.subscription.billTo.city) && request.subscription.billTo.city.Length > 40) { request.subscription.billTo.city = request.subscription.billTo.city.Substring(0, 40); } if (!String.IsNullOrEmpty(request.subscription.billTo.state) && request.subscription.billTo.state.Length > 2) { request.subscription.billTo.state = request.subscription.billTo.state.Substring(0, 2); } if (!String.IsNullOrEmpty(request.subscription.billTo.zip) && request.subscription.billTo.zip.Length > 20) { request.subscription.billTo.zip = request.subscription.billTo.zip.Substring(0, 20); } if (!String.IsNullOrEmpty(request.subscription.billTo.country) && request.subscription.billTo.country.Length > 60) { request.subscription.billTo.country = request.subscription.billTo.country.Substring(0, 60); } } if (request.subscription.shipTo != null) { if (request.subscription.shipTo.firstName.Length > 50) { request.subscription.shipTo.firstName = request.subscription.shipTo.firstName.Substring(0, 50); } if (request.subscription.shipTo.lastName.Length > 50) { request.subscription.shipTo.lastName = request.subscription.shipTo.lastName.Substring(0, 50); } if (request.subscription.shipTo.company.Length > 50) { request.subscription.shipTo.company = request.subscription.shipTo.company.Substring(0, 50); } if (request.subscription.shipTo.address.Length > 60) { request.subscription.shipTo.address = request.subscription.shipTo.address.Substring(0, 60); } if (request.subscription.shipTo.city.Length > 40) { request.subscription.shipTo.city = request.subscription.shipTo.city.Substring(0, 40); } if (request.subscription.shipTo.state.Length > 40) { request.subscription.shipTo.state = request.subscription.shipTo.state.Substring(0, 40); } if (request.subscription.shipTo.zip.Length > 20) { request.subscription.shipTo.zip = request.subscription.shipTo.zip.Substring(0, 20); } if (request.subscription.shipTo.country.Length > 60) { request.subscription.shipTo.country = request.subscription.shipTo.country.Substring(0, 60); } } } }
public void SampleCodeGetSubscriptionList() { LogHelper.info(Logger, "Sample GetSubscriptionList"); ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = CustomMerchantAuthenticationType; ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment = TestEnvironment; //create a subscription var createRequest = new ARBCreateSubscriptionRequest { refId = RefId, subscription = ArbSubscriptionOne, }; var createController = new ARBCreateSubscriptionController(createRequest); createController.RequestId = Guid.NewGuid(); createController.Execute(); var createResponse = createController.GetApiResponse(); Assert.IsNotNull(createResponse.subscriptionId); LogHelper.info(Logger, "Created Subscription: {0}", createResponse.subscriptionId); var subscriptionId = createResponse.subscriptionId; //get subscription details var getRequest = new ARBGetSubscriptionStatusRequest { refId = RefId, subscriptionId = subscriptionId }; var getController = new ARBGetSubscriptionStatusController(getRequest); var getResponse = getController.ExecuteWithApiResponse(); Assert.IsNotNull(getResponse.status); Logger.info(String.Format("Subscription Status: {0}", getResponse.status)); //get subscription list that contains only the subscription created above. var listRequest = new ARBGetSubscriptionListRequest { refId = RefId, searchType = ARBGetSubscriptionListSearchTypeEnum.subscriptionActive, sorting = new ARBGetSubscriptionListSorting { orderDescending = true, orderBy = ARBGetSubscriptionListOrderFieldEnum.createTimeStampUTC, }, paging = new Paging { limit = 500, offset = 1, }, }; var listController = new ARBGetSubscriptionListController(listRequest); var listResponse = listController.ExecuteWithApiResponse(); LogHelper.info(Logger, "Subscription Count: {0}", listResponse.totalNumInResultSet); Assert.IsTrue(0 < listResponse.totalNumInResultSet); //validation of list var subscriptionsArray = listResponse.subscriptionDetails; foreach (var aSubscription in subscriptionsArray) { Assert.IsTrue(0 < aSubscription.id); LogHelper.info(Logger, "Subscription Id: {0}, Status:{1}, PaymentMethod: {2}, Amount: {3}, Account:{4}", aSubscription.id, aSubscription.status, aSubscription.paymentMethod, aSubscription.amount, aSubscription.accountNumber); } //cancel subscription var cancelRequest = new ARBCancelSubscriptionRequest { merchantAuthentication = CustomMerchantAuthenticationType, refId = RefId, subscriptionId = subscriptionId }; var cancelController = new ARBCancelSubscriptionController(cancelRequest); var cancelResponse = cancelController.ExecuteWithApiResponse(TestEnvironment); Assert.IsNotNull(cancelResponse.messages); Logger.info(String.Format("Subscription Cancelled: {0}", subscriptionId)); }
/// <summary> /// Process recurring payment /// </summary> /// <param name="processPaymentRequest">Payment info required for an order processing</param> /// <returns>Process payment result</returns> public ProcessPaymentResult ProcessRecurringPayment(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 }; var billTo = _authorizeNetPaymentSettings.UseShippingAddressAsBilling && customer.ShippingAddress != null?GetRecurringTransactionRequestAddress(customer.ShippingAddress) : GetRecurringTransactionRequestAddress(customer.BillingAddress); var dtNow = DateTime.UtcNow; // Interval can't be updated once a subscription is created. var paymentScheduleInterval = new paymentScheduleTypeInterval(); switch (processPaymentRequest.RecurringCyclePeriod) { case RecurringProductCyclePeriod.Days: paymentScheduleInterval.length = Convert.ToInt16(processPaymentRequest.RecurringCycleLength); paymentScheduleInterval.unit = ARBSubscriptionUnitEnum.days; break; case RecurringProductCyclePeriod.Weeks: paymentScheduleInterval.length = Convert.ToInt16(processPaymentRequest.RecurringCycleLength * 7); paymentScheduleInterval.unit = ARBSubscriptionUnitEnum.days; break; case RecurringProductCyclePeriod.Months: paymentScheduleInterval.length = Convert.ToInt16(processPaymentRequest.RecurringCycleLength); paymentScheduleInterval.unit = ARBSubscriptionUnitEnum.months; break; case RecurringProductCyclePeriod.Years: paymentScheduleInterval.length = Convert.ToInt16(processPaymentRequest.RecurringCycleLength * 12); paymentScheduleInterval.unit = ARBSubscriptionUnitEnum.months; break; default: throw new NopException("Not supported cycle period"); } var paymentSchedule = new paymentScheduleType { startDate = new DateTime(dtNow.Year, dtNow.Month, dtNow.Day), totalOccurrences = Convert.ToInt16(processPaymentRequest.RecurringTotalCycles), interval = paymentScheduleInterval }; var subscriptionType = new ARBSubscriptionType { name = processPaymentRequest.OrderGuid.ToString(), amount = Math.Round(processPaymentRequest.OrderTotal, 2), payment = paymentType, billTo = billTo, paymentSchedule = paymentSchedule, customer = new customerType { email = customer.BillingAddress.Email //phone number should be in one of following formats: 111- 111-1111 or (111) 111-1111. //phoneNumber = customer.BillingAddress.PhoneNumber }, order = new orderType { //x_invoice_num is 20 chars maximum. Hence we also pass x_description invoiceNumber = processPaymentRequest.OrderGuid.ToString().Substring(0, 20), description = $"Recurring payment #{processPaymentRequest.OrderGuid}" } }; if (customer.ShippingAddress != null && !_authorizeNetPaymentSettings.UseShippingAddressAsBilling) { var shipTo = GetRecurringTransactionRequestAddress(customer.ShippingAddress); subscriptionType.shipTo = shipTo; } var request = new ARBCreateSubscriptionRequest { subscription = subscriptionType }; // instantiate the controller that will call the service var controller = new ARBCreateSubscriptionController(request); controller.Execute(); // get the response from the service (errors contained if any) var response = controller.GetApiResponse(); //validate if (response != null && response.messages.resultCode == messageTypeEnum.Ok) { result.SubscriptionTransactionId = response.subscriptionId; result.AuthorizationTransactionCode = response.refId; result.AuthorizationTransactionResult = $"Approved ({response.refId}: {response.subscriptionId})"; } else if (response != null) { foreach (var responseMessage in response.messages.message) { result.AddError( $"Error processing recurring payment #{responseMessage.code}: {responseMessage.text}"); } } else { result.AddError("Authorize.NET unknown error"); } return(result); }
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); }
/// <summary> /// Fill in the given request with test data to create a new subscription. /// </summary> /// <param name="payment">The payment object.</param> private static ARBCreateSubscriptionRequest PopulateCreateSubscriptionRequest(CreditCardPayment payment) { ARBCreateSubscriptionRequest request = new ARBCreateSubscriptionRequest(); PaymentPlan plan = (PaymentPlan)payment.Parent.Parent; ARBSubscriptionType sub = new ARBSubscriptionType(); creditCardType creditCard = new creditCardType(); sub.name = CoreConfiguration.Instance.DefaultApplicationName + " - subscription"; creditCard.cardNumber = payment.CreditCardNumber; creditCard.expirationDate = String.Format("{0:d4}-{1:d2}", payment.ExpirationYear, payment.ExpirationMonth); // required format for API is YYYY-MM sub.payment = new paymentType(); sub.payment.Item = creditCard; // Find the address OrderAddress address = null; foreach (OrderAddress a in plan.OrderAddresses) { if (a.Name == payment.BillingAddressId) { address = a; break; } } sub.billTo = new nameAndAddressType(); sub.billTo.firstName = address.FirstName; sub.billTo.lastName = address.LastName; // Create a subscription sub.paymentSchedule = new paymentScheduleType(); sub.paymentSchedule.startDate = plan.StartDate; sub.paymentSchedule.startDateSpecified = true; sub.paymentSchedule.totalOccurrences = Convert.ToInt16(plan.MaxCyclesCount); sub.paymentSchedule.totalOccurrencesSpecified = true; // free 1 month trial //sub.paymentSchedule.trialOccurrences = 1; //sub.paymentSchedule.trialOccurrencesSpecified = true; //sub.trialAmount = 0.00M; //sub.trialAmountSpecified = true; sub.amount = GetSumInUSD(payment.Amount, plan.BillingCurrency); sub.amountSpecified = true; sub.paymentSchedule.interval = GetRecurringPaymentTypeInterval(plan); sub.order = new orderType(); sub.order.invoiceNumber = plan.OrderGroupId.ToString(); sub.customer = new customerType(); sub.customer.email = address.Email; request.subscription = sub; return(request); }