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); } }
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()); }
/// <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 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)); }
//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); }
/// <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 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.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)); }
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); } }
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); } } }
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 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); } } }
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 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()); }
public static void Run(String ApiLoginID, String ApiTransactionKey, string RefID) { 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 = 1; // 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 }; #region Payment Information var creditCard = new creditCardType { cardNumber = "4111111111111111", expirationDate = "0718" }; //standard api call to retrieve response paymentType cc = new paymentType { Item = creditCard }; #endregion nameAndAddressType addressInfo = new nameAndAddressType() { firstName = "Calvin", lastName = "Brown" }; ARBSubscriptionType subscriptionType = new ARBSubscriptionType() { amount = 35.55m, paymentSchedule = schedule, billTo = addressInfo, payment = cc }; var request = new ARBCreateSubscriptionRequest { refId = RefID, 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 Code : " + response.subscriptionId.ToString()); } } else { Console.WriteLine("Error: " + response.messages.message[0].code + " " + response.messages.message[0].text); } }
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)); }