コード例 #1
0
        /// <summary>
        /// Returns paymentScheduleTypeInterval objct based on <paramref name="plan"/> parameter values.
        /// </summary>
        /// <param name="plan">The payment plan.</param>
        /// <returns></returns>
        private static paymentScheduleTypeInterval GetRecurringPaymentTypeInterval(PaymentPlan plan)
        {
            paymentScheduleTypeInterval interval = new paymentScheduleTypeInterval();

            if (plan.CycleMode == PaymentPlanCycle.Days)
            {
                interval.unit = ARBSubscriptionUnitEnum.days;
            }
            else if (plan.CycleMode == PaymentPlanCycle.Months)
            {
                interval.unit = ARBSubscriptionUnitEnum.months;
            }
            else
            {
                throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "", "Plan CycleMode is not supported.");
            }

            interval.length = Convert.ToInt16(plan.CycleLength);

            return(interval);
        }
コード例 #2
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);
        }
コード例 #3
0
        /// <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);
        }
コード例 #4
0
        public void SetUp()
        {
            MockContext = new MockFactory();

            //initialize counter
            Counter    = _random.Next(1, (int)(Math.Pow(2, 24)));
            CounterStr = GetRandomString("");

            _now       = DateTime.UtcNow;
            _nowString = _now.ToString(DateFormat);

            _pastDate   = _now.AddMonths(-1);
            _nowDate    = _now;
            _futureDate = _now.AddMonths(1);

            CustomMerchantAuthenticationType = new merchantAuthenticationType
            {
                name            = ApiLoginIdKey,
                ItemElementName = ItemChoiceType.transactionKey,
                Item            = TransactionKey,
            };

            //		merchantAuthenticationType.setSessionToken(GetRandomString("SessionToken"));
            //		merchantAuthenticationType.setPass_word(GetRandomString("Pass_word"));
            //	    merchantAuthenticationType.setMobileDeviceId(GetRandomString("MobileDevice"));

            //	    ImpersonationAuthenticationType impersonationAuthenticationType = new ImpersonationAuthenticationType();
            //	    impersonationAuthenticationType.setPartnerLoginId(CnpApiLoginIdKey);
            //	    impersonationAuthenticationType.setPartnerTransactionKey(CnpTransactionKey);
            //	    merchantAuthenticationType.setImpersonationAuthentication(impersonationAuthenticationType);

            CustomerProfileType = new customerProfileType
            {
                merchantCustomerId = GetRandomString("Customer"),
                description        = GetRandomString("CustomerDescription"),
                email = CounterStr + "*****@*****.**",
            };

            //make sure these elements are initialized by calling get as it uses lazy initialization
            var paymentProfiles = CustomerProfileType.paymentProfiles;
            var addresses       = CustomerProfileType.shipToList;

            CreditCardOne = new creditCardType
            {
                cardNumber     = "4111111111111111",
                expirationDate = "2038-12",
            };
            //		creditCardOne.setCardCode("");

            BankAccountOne = new bankAccountType
            {
                accountType   = bankAccountTypeEnum.savings,
                routingNumber = "125000000",
                accountNumber = GetRandomString("A/C#"),
                nameOnAccount = GetRandomString("A/CName"),
                echeckType    = echeckTypeEnum.WEB,
                bankName      = GetRandomString("Bank"),
                checkNumber   = CounterStr,
            };

            TrackDataOne = new creditCardTrackType
            {
                ItemElementName = ItemChoiceType1.track1,
                Item            = GetRandomString("Track1"),
                //trackDataOne.setTrack2(GetRandomString("Track2"));
            };

            EncryptedTrackDataOne = new encryptedTrackDataType
            {
                FormOfPayment = new KeyBlock(),
            };
            //keyBlock.setValue(value);

            PayPalOne = new payPalType
            {
                successUrl         = GetRandomString("https://success.anet.net"),
                cancelUrl          = GetRandomString("https://cancel.anet.net"),
                paypalLc           = GetRandomString("Lc"),
                paypalHdrImg       = GetRandomString("Hdr"),
                paypalPayflowcolor = GetRandomString("flowClr"),
                payerID            = GetRandomString("PayerId"),
            };

            PaymentOne = new paymentType
            {
                Item = CreditCardOne
            };
            //paymentOne.setBankAccount(bankAccountOne);
            //paymentOne.setTrackData(trackDataOne);
            //paymentOne.setEncryptedTrackData(encryptedTrackDataOne);
            //paymentOne.setPayPal( payPalOne);

            //		driversLicenseOne = new DriversLicenseType();
            //		driversLicenseOne.setNumber(GetRandomString("DLNumber"));
            //		driversLicenseOne.setState(GetRandomString("WA"));
            //		driversLicenseOne.setDateOfBirth(nowString);

            CustomerAddressOne = new customerAddressType
            {
                firstName   = GetRandomString("FName"),
                lastName    = GetRandomString("LName"),
                company     = GetRandomString("Company"),
                address     = GetRandomString("StreetAdd"),
                city        = "Bellevue",
                state       = "WA",
                zip         = "98000",
                country     = "USA",
                phoneNumber = FormatToPhone(Counter),
                faxNumber   = FormatToPhone(Counter + 1),
            };

            CustomerPaymentProfileOne = new customerPaymentProfileType
            {
                customerType = customerTypeEnum.individual,
                payment      = PaymentOne,
            };
            //	    customerPaymentProfileOne.setBillTo(customerAddressOne);
            //	    customerPaymentProfileOne.setDriversLicense(driversLicenseOne);
            //	    customerPaymentProfileOne.setTaxId(GetRandomString("XX"));


            CustomerOne = new customerType
            {
                type           = customerTypeEnum.individual,
                id             = GetRandomString("Id"),
                email          = CounterStr + "*****@*****.**",
                phoneNumber    = FormatToPhone(Counter),
                faxNumber      = FormatToPhone(Counter + 1),
                driversLicense = DriversLicenseOne,
                taxId          = "911011011",
            };

            CustomerTwo = new customerType();

            var interval = new paymentScheduleTypeInterval
            {
                length = 1,
                unit   = ARBSubscriptionUnitEnum.months,
            };

            OrderType = new orderType()
            {
                //TODO ADD VALIDATION ON INVOICE LENGTH
                invoiceNumber = GetRandomString("Inv:"),
                description   = GetRandomString("Description"),
            };

            NameAndAddressTypeOne = new nameAndAddressType
            {
                firstName = GetRandomString("FName"),
                lastName  = GetRandomString("LName"),
                company   = GetRandomString("Company"),
                address   = GetRandomString("Address"),
                city      = GetRandomString("City"),
                state     = GetRandomString("State"),
                zip       = "98004",
                country   = "USA",
            };

            NameAndAddressTypeTwo = new nameAndAddressType
            {
                firstName = GetRandomString("FName"),
                lastName  = GetRandomString("LName"),
                company   = GetRandomString("Company"),
                address   = GetRandomString("Address"),
                city      = GetRandomString("City"),
                state     = GetRandomString("State"),
                zip       = "98004",
                country   = "USA",
            };

            PaymentScheduleTypeOne = new paymentScheduleType
            {
                interval         = interval,
                startDate        = _nowDate,
                totalOccurrences = 5,
                trialOccurrences = 0,
            };

            ArbSubscriptionOne = new ARBSubscriptionType
            {
                amount          = SetValidSubscriptionAmount(Counter),
                billTo          = NameAndAddressTypeOne,
                customer        = CustomerOne,
                name            = GetRandomString("Name"),
                order           = OrderType,
                payment         = PaymentOne,
                paymentSchedule = PaymentScheduleTypeOne,
                shipTo          = NameAndAddressTypeOne,
                trialAmount     = SetValidSubscriptionAmount(0),
            };

            CustomerDataOne = new customerDataType
            {
                driversLicense = CustomerOne.driversLicense,
                email          = CustomerOne.email,
                id             = CustomerOne.id,
                taxId          = CustomerOne.taxId,
                type           = CustomerOne.type,
            };

            RefId = CounterStr;
        }
コード例 #5
0
 public static void paymentScheduleTypeInterval(paymentScheduleTypeInterval request)
 {
 }
コード例 #6
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 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);
                        }
                    }
                }
            }
        }
コード例 #7
0
        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);
        }
コード例 #9
0
        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);
            }
        }