Пример #1
0
        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);
        }
Пример #2
0
        public static ANetApiResponse Run(string ApiLoginID, string ApiTransactionKey, string subscriptionId)
        {
            Console.WriteLine("Update Subscription Sample");

            ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment         = AuthorizeNET.Environment.SANDBOX;
            ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = new merchantAuthenticationType()
            {
                name            = ApiLoginID,
                ItemElementName = ItemChoiceType.transactionKey,
                Item            = ApiTransactionKey,
            };

            paymentScheduleType schedule = new paymentScheduleType
            {
                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"
            };

            customerProfileIdType customerProfile = new customerProfileIdType()
            {
                customerProfileId        = "1232312",
                customerPaymentProfileId = "2132132",
                customerAddressId        = "1233432"
            };

            ARBSubscriptionType subscriptionType = new ARBSubscriptionType()
            {
                amount          = 35.55m,
                paymentSchedule = schedule,
                billTo          = addressInfo,
                payment         = cc
                                  //You can pass a profile to update subscription
                                  //,profile = customerProfile
            };

            //Please change the subscriptionId according to your request
            var request = new ARBUpdateSubscriptionRequest {
                subscription = subscriptionType, subscriptionId = subscriptionId
            };
            var controller = new ARBUpdateSubscriptionController(request);
            controller.Execute();

            ARBUpdateSubscriptionResponse response = controller.GetApiResponse();

            //validate
            if (response != null && response.messages.resultCode == messageTypeEnum.Ok)
            {
                if (response != null && response.messages.message != null)
                {
                    Console.WriteLine("Success, RefID Code : " + response.refId);
                }
            }
            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);
                        }
                    }
                }
            }
        }
Пример #4
0
        //public static ANetApiResponse Run(string ApiLoginID, string ApiTransactionKey, string subscriptionId)
        //{
        //    Console.WriteLine("Update Subscription Sample");

        //    ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = AuthorizeNET.Environment.SANDBOX;
        //    ApiOperationBase<ANetApiRequest, ANetApiResponse>.MerchantAuthentication = new merchantAuthenticationType()
        //    {
        //        name = ApiLoginID,
        //        ItemElementName = ItemChoiceType.transactionKey,
        //        Item = ApiTransactionKey,
        //    };

        //    paymentScheduleType schedule = new paymentScheduleType
        //    {
        //        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"
        //    };

        //    customerProfileIdType customerProfile = new customerProfileIdType()
        //    {
        //        customerProfileId = "1232312",
        //        customerPaymentProfileId = "2132132",
        //        customerAddressId = "1233432"
        //    };

        //    ARBSubscriptionType subscriptionType = new ARBSubscriptionType()
        //    {
        //        amount = 35.55m,
        //        paymentSchedule = schedule,
        //        billTo = addressInfo,
        //        payment = cc
        //        //You can pass a profile to update subscription
        //        //,profile = customerProfile
        //    };

        //    //Please change the subscriptionId according to your request
        //    var request = new ARBUpdateSubscriptionRequest { subscription = subscriptionType, subscriptionId = subscriptionId };
        //    var controller = new ARBUpdateSubscriptionController(request);
        //    controller.Execute();

        //    ARBUpdateSubscriptionResponse response = controller.GetApiResponse();

        //    //validate
        //    if (response != null && response.messages.resultCode == messageTypeEnum.Ok)
        //    {
        //        if (response != null && response.messages.message != null)
        //        {
        //            Console.WriteLine("Success, RefID Code : " + response.refId);
        //        }
        //    }
        //    else if(response != null)
        //    {
        //        Console.WriteLine("Error: " + response.messages.message[0].code + "  " + response.messages.message[0].text);
        //    }

        //    return response;
        //}
        public static void UpdateSubscriptionExec(String ApiLoginID, String ApiTransactionKey)
        {
            using (CsvReader csv = new CsvReader(new StreamReader(new FileStream(@"../../../CSV_DATA/CancleASubscription.csv", FileMode.Open)), true))
            {
                Console.WriteLine("Update 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 subscriptionId           = null;
                        string TestCase_Id              = null;
                        string firstName                = null;
                        string lastName                 = null;
                        string customerProfileId        = null;
                        string customerPaymentProfileId = null;
                        string customerAddressId        = null;
                        string amount = null;
                        for (int i = 0; i < fieldCount; i++)
                        {
                            switch (headers[i])
                            {
                            case "subscriptionId":
                                subscriptionId = csv[i];
                                break;

                            case "firstName":
                                firstName = csv[i];
                                break;

                            case "lastName":
                                lastName = csv[i];
                                break;

                            case "customerProfileId":
                                customerProfileId = csv[i];
                                break;

                            case "customerPaymentProfileId":
                                customerPaymentProfileId = csv[i];
                                break;

                            case "customerAddressId":
                                customerAddressId = csv[i];
                                break;

                            case "amount":
                                amount = 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);
                                }
                            }

                            //response = instance.GetCustomer(customerId, authorization);
                            paymentScheduleType schedule = new paymentScheduleType
                            {
                                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 = firstName,
                                lastName  = lastName
                            };

                            customerProfileIdType customerProfile = new customerProfileIdType()
                            {
                                customerProfileId        = customerProfileId,
                                customerPaymentProfileId = customerPaymentProfileId,
                                customerAddressId        = customerAddressId
                            };

                            ARBSubscriptionType subscriptionType = new ARBSubscriptionType()
                            {
                                amount          = Convert.ToDecimal(amount),
                                paymentSchedule = schedule,
                                billTo          = addressInfo,
                                payment         = cc
                                                  //You can pass a profile to update subscription
                                                  //,profile = customerProfile
                            };

                            //Please change the subscriptionId according to your request
                            var request = new ARBUpdateSubscriptionRequest {
                                subscription = subscriptionType, subscriptionId = subscriptionId
                            };
                            var controller = new ARBUpdateSubscriptionController(request);
                            controller.Execute();

                            ARBUpdateSubscriptionResponse 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("UAS_00" + flag.ToString());
                                    row1.Add("UpdateASubscription");
                                    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, RefID Code : " + response.refId);
                                }
                                catch
                                {
                                    CsvRow row1 = new CsvRow();
                                    row1.Add("UAS_00" + flag.ToString());
                                    row1.Add("UpdateASubscription");
                                    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("UAS_00" + flag.ToString());
                                row1.Add("UpdateASubscription");
                                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("UAS_00" + flag.ToString());
                            row2.Add("UpdateASubscription");
                            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>
        /// The Update function won't accept a change to some values - specifically the billing interval. This creates a request
        /// that the API can understand for updates only
        /// </summary>
        /// <returns></returns>
        public ARBSubscriptionType ToUpdateableAPI()
        {
            var sub = new ARBSubscriptionType();

            sub.name = this.SubscriptionName;

            if (!String.IsNullOrEmpty(this.CardNumber) && (this.CardNumber.Trim().Length > 0))
            {
                DateTime dt;
                if (!CommonFunctions.ParseDateTime(this.CardExpirationYear, this.CardExpirationMonth, 1, out dt))
                {
                    throw new InvalidOperationException("Need a valid CardExpirationMonth and CardExpirationYear to set up this subscription");
                }

                var creditCard = new creditCardType
                {
                    cardNumber     = this.CardNumber,
                    expirationDate = dt.ToString("yyyy-MM")
                };
                //string.Format("{0}-{1}", this.CardExpirationYear, this.CardExpirationMonth);  // required format for API is YYYY-MM
                sub.payment = new paymentType {
                    Item = creditCard
                };
            }

            if ((this.eCheckBankAccount != null) && !String.IsNullOrEmpty(this.eCheckBankAccount.accountNumber) &&
                (this.eCheckBankAccount.accountNumber.Trim().Length > 0))
            {
                var eCheck = new bankAccountType()
                {
                    accountTypeSpecified = eCheckBankAccount.accountTypeSpecified,
                    accountType          = (bankAccountTypeEnum)Enum.Parse(typeof(bankAccountTypeEnum), eCheckBankAccount.accountType.ToString(), true),
                    routingNumber        = eCheckBankAccount.routingNumber,
                    accountNumber        = eCheckBankAccount.accountNumber,
                    nameOnAccount        = eCheckBankAccount.nameOnAccount,
                    echeckTypeSpecified  = eCheckBankAccount.echeckTypeSpecified,
                    echeckType           = (echeckTypeEnum)Enum.Parse(typeof(echeckTypeEnum), eCheckBankAccount.echeckType.ToString(), true),
                    bankName             = eCheckBankAccount.bankName,
                    checkNumber          = eCheckBankAccount.checkNumber
                };
                sub.payment = new paymentType {
                    Item = eCheck
                };
            }

            if (!String.IsNullOrEmpty(this.CustomerProfileId) && !String.IsNullOrEmpty(this.CustomerPaymentProfileId))
            {
                var customerProfile = new customerProfileIdType
                {
                    customerProfileId        = this.CustomerProfileId,
                    customerPaymentProfileId = this.CustomerPaymentProfileId,
                    customerAddressId        = this.CustomerAddressId
                };

                sub.profile = customerProfile;
            }
            else
            {
                sub.customer = new customerType
                {
                    email = this.CustomerEmail,
                    id    = this.CustomerID
                };
            }

            if (this.BillingAddress != null)
            {
                sub.billTo = this.BillingAddress.ToAPINameAddressType();
            }
            if (this.ShippingAddress != null)
            {
                sub.shipTo = this.ShippingAddress.ToAPINameAddressType();
            }

            sub.paymentSchedule = new paymentScheduleType
            {
                totalOccurrences          = this.BillingCycles,
                totalOccurrencesSpecified = true
            };

            sub.amount          = this.Amount;
            sub.amountSpecified = true;



            sub.order = new orderType
            {
                description   = this.Description,
                invoiceNumber = this.Invoice
            };

            return(sub);
        }
        /// <summary>
        /// This is mostly for internal processing needs - it takes the SubscriptionRequest and turns it into something the Gateway can serialize.
        /// </summary>
        /// <returns></returns>
        public ARBSubscriptionType ToAPI()
        {
            var sub = new ARBSubscriptionType();

            sub.name = this.SubscriptionName;

            bool          isCardValid    = false;
            bool          isBankValid    = false;
            bool          isProfileValid = false;
            StringBuilder sbError        = new StringBuilder("");
            bool          bError         = false;


            if (!String.IsNullOrEmpty(this.CardNumber) &&
                this.CardNumber.Trim().Length == 0)
            {
                isCardValid = true;
            }
            else if (this.eCheckBankAccount != null &&
                     !String.IsNullOrEmpty(this.eCheckBankAccount.accountNumber) &&
                     this.eCheckBankAccount.accountNumber.Trim().Length != 0)
            {
                isBankValid = true;
            }
            else if (!String.IsNullOrEmpty(this.CustomerProfileId) &&
                     !String.IsNullOrEmpty(this.CustomerPaymentProfileId))
            {
                isProfileValid = true;
            }

            if (!(isCardValid || isBankValid || isProfileValid))
            {
                sbError.Append("Need a credit card number or a bank account number to set up this subscription");
                bError = true;
            }

            DateTime dt = new DateTime();

            if (isCardValid && !CommonFunctions.ParseDateTime(this.CardExpirationYear, this.CardExpirationMonth, 1, out dt))
            {
                sbError.Append("Need a valid CardExpirationMonth and CardExpirationYear to set up this subscription");
                bError = true;
            }

            if (bError)
            {
                throw new InvalidOperationException(sbError.ToString());
            }

            if (isCardValid)
            {
                var creditCard = new creditCardType
                {
                    cardNumber = this.CardNumber,
                    // required format for API is YYYY-MM
                    expirationDate = dt.ToString("yyyy-MM")
                };
                sub.payment = new paymentType {
                    Item = creditCard
                };
            }
            else if (isBankValid)
            {
                var eCheck = new bankAccountType()
                {
                    accountTypeSpecified = eCheckBankAccount.accountTypeSpecified,
                    accountType          = (bankAccountTypeEnum)Enum.Parse(typeof(bankAccountTypeEnum), eCheckBankAccount.accountType.ToString(), true),
                    routingNumber        = eCheckBankAccount.routingNumber,
                    accountNumber        = eCheckBankAccount.accountNumber,
                    nameOnAccount        = eCheckBankAccount.nameOnAccount,
                    echeckTypeSpecified  = eCheckBankAccount.echeckTypeSpecified,
                    echeckType           = (echeckTypeEnum)Enum.Parse(typeof(echeckTypeEnum), eCheckBankAccount.echeckType.ToString(), true),
                    bankName             = eCheckBankAccount.bankName,
                    checkNumber          = eCheckBankAccount.checkNumber
                };
                sub.payment = new paymentType {
                    Item = eCheck
                };
            }
            else if (isProfileValid)
            {
                var customerProfile = new customerProfileIdType
                {
                    customerProfileId        = this.CustomerProfileId,
                    customerPaymentProfileId = this.CustomerPaymentProfileId,
                    customerAddressId        = this.CustomerAddressId
                };

                sub.profile = customerProfile;
            }

            if (this.BillingAddress != null)
            {
                sub.billTo = this.BillingAddress.ToAPINameAddressType();
            }
            if (this.ShippingAddress != null)
            {
                sub.shipTo = this.ShippingAddress.ToAPINameAddressType();
            }

            sub.paymentSchedule = new paymentScheduleType
            {
                startDate                 = this.StartsOn,
                startDateSpecified        = true,
                totalOccurrences          = this.BillingCycles,
                totalOccurrencesSpecified = true
            };


            // free 1 month trial
            if (this.TrialBillingCycles >= 0)
            {
                sub.paymentSchedule.trialOccurrences          = this.TrialBillingCycles;
                sub.paymentSchedule.trialOccurrencesSpecified = true;
            }

            if (this.TrialAmount >= 0)
            {
                sub.trialAmount          = this.TrialAmount;
                sub.trialAmountSpecified = true;
            }

            sub.amount          = this.Amount;
            sub.amountSpecified = true;

            sub.paymentSchedule.interval        = new paymentScheduleTypeInterval();
            sub.paymentSchedule.interval.length = this.BillingInterval;

            if (this.BillingIntervalUnits == BillingIntervalUnits.Months)
            {
                sub.paymentSchedule.interval.unit = ARBSubscriptionUnitEnum.months;
            }
            else
            {
                sub.paymentSchedule.interval.unit = ARBSubscriptionUnitEnum.days;
            }
            if (!isProfileValid)
            {
                sub.customer = new customerType
                {
                    email = this.CustomerEmail,
                    id    = this.CustomerID
                };
            }

            sub.order = new orderType
            {
                description   = this.Description,
                invoiceNumber = this.Invoice
            };

            return(sub);
        }