/// <summary>
        /// Process recurring payment
        /// </summary>
        /// <param name="paymentInfo">Payment info required for an order processing</param>
        /// <param name="customer">Customer</param>
        /// <param name="orderGuid">Unique order identifier</param>
        /// <param name="processPaymentResult">Process payment result</param>
        public void ProcessRecurringPayment(PaymentInfo paymentInfo, Customer customer, Guid orderGuid, ref ProcessPaymentResult processPaymentResult)
        {
            InitSettings();
            MerchantAuthenticationType authentication = PopulateMerchantAuthentication();
            if (!paymentInfo.IsRecurringPayment)
            {
                ARBSubscriptionType subscription = new ARBSubscriptionType();
                NopSolutions.NopCommerce.Payment.Methods.AuthorizeNet.net.authorize.api.CreditCardType creditCard = new NopSolutions.NopCommerce.Payment.Methods.AuthorizeNet.net.authorize.api.CreditCardType();

                subscription.name = orderGuid.ToString();

                creditCard.cardNumber = paymentInfo.CreditCardNumber;
                creditCard.expirationDate = paymentInfo.CreditCardExpireYear + "-" + paymentInfo.CreditCardExpireMonth; // required format for API is YYYY-MM
                creditCard.cardCode = paymentInfo.CreditCardCvv2;

                subscription.payment = new PaymentType();
                subscription.payment.Item = creditCard;

                subscription.billTo = new NameAndAddressType();
                subscription.billTo.firstName = paymentInfo.BillingAddress.FirstName;
                subscription.billTo.lastName = paymentInfo.BillingAddress.LastName;
                subscription.billTo.address = paymentInfo.BillingAddress.Address1 + " " + paymentInfo.BillingAddress.Address2;
                subscription.billTo.city = paymentInfo.BillingAddress.City;
                if (paymentInfo.BillingAddress.StateProvince != null)
                {
                    subscription.billTo.state = paymentInfo.BillingAddress.StateProvince.Abbreviation;
                }
                subscription.billTo.zip = paymentInfo.BillingAddress.ZipPostalCode;

                if (paymentInfo.ShippingAddress != null)
                {
                    subscription.shipTo = new NameAndAddressType();
                    subscription.shipTo.firstName = paymentInfo.ShippingAddress.FirstName;
                    subscription.shipTo.lastName = paymentInfo.ShippingAddress.LastName;
                    subscription.shipTo.address = paymentInfo.ShippingAddress.Address1 + " " + paymentInfo.ShippingAddress.Address2;
                    subscription.shipTo.city = paymentInfo.ShippingAddress.City;
                    if (paymentInfo.ShippingAddress.StateProvince != null)
                    {
                        subscription.shipTo.state = paymentInfo.ShippingAddress.StateProvince.Abbreviation;
                    }
                    subscription.shipTo.zip = paymentInfo.ShippingAddress.ZipPostalCode;

                }

                subscription.customer = new CustomerType();
                subscription.customer.email = customer.BillingAddress.Email;
                subscription.customer.phoneNumber = customer.BillingAddress.PhoneNumber;

                subscription.order = new OrderType();
                subscription.order.description = string.Format("{0} {1}", IoC.Resolve<ISettingManager>().StoreName, "Recurring payment");

                // Create a subscription that is leng of specified occurrences and interval is amount of days ad runs

                subscription.paymentSchedule = new PaymentScheduleType();
                DateTime dtNow = DateTime.UtcNow;
                subscription.paymentSchedule.startDate = new DateTime(dtNow.Year, dtNow.Month, dtNow.Day);
                subscription.paymentSchedule.startDateSpecified = true;

                subscription.paymentSchedule.totalOccurrences = Convert.ToInt16(paymentInfo.RecurringTotalCycles);
                subscription.paymentSchedule.totalOccurrencesSpecified = true;

                subscription.amount = paymentInfo.OrderTotal;
                subscription.amountSpecified = true;

                // Interval can't be updated once a subscription is created.
                subscription.paymentSchedule.interval = new PaymentScheduleTypeInterval();
                switch (paymentInfo.RecurringCyclePeriod)
                {
                    case (int)RecurringProductCyclePeriodEnum.Days:
                        subscription.paymentSchedule.interval.length = Convert.ToInt16(paymentInfo.RecurringCycleLength);
                        subscription.paymentSchedule.interval.unit = ARBSubscriptionUnitEnum.days;
                        break;
                    case (int)RecurringProductCyclePeriodEnum.Weeks:
                        subscription.paymentSchedule.interval.length = Convert.ToInt16(paymentInfo.RecurringCycleLength * 7);
                        subscription.paymentSchedule.interval.unit = ARBSubscriptionUnitEnum.days;
                        break;
                    case (int)RecurringProductCyclePeriodEnum.Months:
                        subscription.paymentSchedule.interval.length = Convert.ToInt16(paymentInfo.RecurringCycleLength);
                        subscription.paymentSchedule.interval.unit = ARBSubscriptionUnitEnum.months;
                        break;
                    case (int)RecurringProductCyclePeriodEnum.Years:
                        subscription.paymentSchedule.interval.length = Convert.ToInt16(paymentInfo.RecurringCycleLength * 12);
                        subscription.paymentSchedule.interval.unit = ARBSubscriptionUnitEnum.months;
                        break;
                    default:
                        throw new NopException("Not supported cycle period");
                }

                ARBCreateSubscriptionResponseType response = webService.ARBCreateSubscription(authentication, subscription);

                if (response.resultCode == MessageTypeEnum.Ok)
                {
                    processPaymentResult.SubscriptionTransactionId = response.subscriptionId.ToString();
                    processPaymentResult.AuthorizationTransactionCode = response.resultCode.ToString();
                    processPaymentResult.AuthorizationTransactionResult = string.Format("Approved ({0}: {1})", response.resultCode.ToString(), response.subscriptionId.ToString());
                }
                else
                {
                    processPaymentResult.Error = string.Format("Error processing recurring payment. {0}", GetErrors(response));
                    processPaymentResult.FullError = string.Format("Error processing recurring payment. {0}", GetErrors(response));
                }
            }
        }
        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"
            };

            ARBSubscriptionType subscriptionType = new ARBSubscriptionType()
            {
                amount          = 35.55m,
                paymentSchedule = schedule,
                billTo          = addressInfo,
                payment         = cc
            };

            //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);
        }
예제 #3
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.setPassword(GetRandomString("Password"));
            //	    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;
        }
예제 #4
0
        //public static ANetApiResponse Run(String ApiLoginID, String ApiTransactionKey, short intervalLength)
        //{
        //    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

        //    nameAndAddressType addressInfo = new nameAndAddressType()
        //    {
        //        firstName = "John",
        //        lastName = "Doe"
        //    };

        //    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)

        //    //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 CreateSubscriptionExec(String ApiLoginID, String ApiTransactionKey)
        {
            using (CsvReader csv = new CsvReader(new StreamReader(new FileStream(@"../../../CSV_DATA/CreateASubscription.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 length      = null;
                        string TestCase_Id = null;

                        string amount = null;
                        for (int i = 0; i < fieldCount; i++)
                        {
                            switch (headers[i])
                            {
                            case "length":
                                length = 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);
                                }
                            }
                            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

                            nameAndAddressType addressInfo = new nameAndAddressType()
                            {
                                firstName = "John",
                                lastName  = "Doe"
                            };

                            ARBSubscriptionType subscriptionType = new ARBSubscriptionType()
                            {
                                amount          = Convert.ToDecimal(amount),
                                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();



                            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("CS_00" + flag.ToString());
                                    row1.Add("CreateSubscription");
                                    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("CS_00" + flag.ToString());
                                    row1.Add("CreateSubscription");
                                    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("CS_00" + flag.ToString());
                                row1.Add("CreateSubscription");
                                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("CS_00" + flag.ToString());
                            row2.Add("CreateSubscription");
                            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 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);
        }
예제 #6
0
        public void TestErrorMessages_ARB_ExpiredCard()
        {
            var rnd = new AnetRandom(DateTime.Now.Millisecond);

            ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = CustomMerchantAuthenticationType;
            ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment         = TestEnvironment;


            //create a subscription with an invalid (expired) credit card in payment.
            var subscriptionDef = new ARBSubscriptionType
            {
                paymentSchedule = new paymentScheduleType
                {
                    interval = new paymentScheduleTypeInterval
                    {
                        length = 7,
                        unit   = ARBSubscriptionUnitEnum.days
                    },
                    startDate        = DateTime.UtcNow,
                    totalOccurrences = 2,
                },


                amount = SetValidSubscriptionAmount(Counter),
                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     = "4111111111111111",
                        expirationDate = "122013",              //deliberatly set payment to use expired CC
                    }
                },

                customer = new customerType {
                    email = "*****@*****.**", id = "5",
                },

                order = new orderType {
                    description = string.Format("member monthly {0}", rnd.Next(99999))
                },
            };

            var arbRequest = new ARBCreateSubscriptionRequest {
                subscription = subscriptionDef
            };
            var arbController = new ARBCreateSubscriptionController(arbRequest);

            arbController.Execute();

            var arbCreateResponse = arbController.GetApiResponse();

            //If request responds with an error, walk the messages and get code and text for each message.
            if (arbController.GetResultCode() == messageTypeEnum.Error)
            {
                foreach (var msg in arbCreateResponse.messages.message)
                {
                    Console.WriteLine("Error Num = {0}, Message = {1}", msg.code, msg.text);
                }
            }
        }
        /// <summary>
        /// Process recurring payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public ProcessPaymentResult ProcessRecurringPayment(ProcessPaymentRequest processPaymentRequest)
        {
            var result = new ProcessPaymentResult();

            if (!processPaymentRequest.IsRecurringPayment)
            {
                var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);

                var subscription = new ARBSubscriptionType();
                var creditCard   = new net.authorize.api.CreditCardType();

                subscription.name = processPaymentRequest.OrderGuid.ToString();

                creditCard.cardNumber     = processPaymentRequest.CreditCardNumber;
                creditCard.expirationDate = processPaymentRequest.CreditCardExpireYear + "-" + processPaymentRequest.CreditCardExpireMonth; // required format for API is YYYY-MM
                creditCard.cardCode       = processPaymentRequest.CreditCardCvv2;

                subscription.payment      = new PaymentType();
                subscription.payment.Item = creditCard;

                subscription.billTo           = new NameAndAddressType();
                subscription.billTo.firstName = customer.BillingAddress.FirstName;
                subscription.billTo.lastName  = customer.BillingAddress.LastName;
                subscription.billTo.address   = customer.BillingAddress.Address1 + " " + customer.BillingAddress.Address2;
                subscription.billTo.city      = customer.BillingAddress.City;
                if (customer.BillingAddress.StateProvince != null)
                {
                    subscription.billTo.state = customer.BillingAddress.StateProvince.Abbreviation;
                }
                subscription.billTo.zip = customer.BillingAddress.ZipPostalCode;

                if (customer.ShippingAddress != null)
                {
                    subscription.shipTo           = new NameAndAddressType();
                    subscription.shipTo.firstName = customer.ShippingAddress.FirstName;
                    subscription.shipTo.lastName  = customer.ShippingAddress.LastName;
                    subscription.shipTo.address   = customer.ShippingAddress.Address1 + " " + customer.ShippingAddress.Address2;
                    subscription.shipTo.city      = customer.ShippingAddress.City;
                    if (customer.ShippingAddress.StateProvince != null)
                    {
                        subscription.shipTo.state = customer.ShippingAddress.StateProvince.Abbreviation;
                    }
                    subscription.shipTo.zip = customer.ShippingAddress.ZipPostalCode;
                }

                subscription.customer             = new CustomerType();
                subscription.customer.email       = customer.BillingAddress.Email;
                subscription.customer.phoneNumber = customer.BillingAddress.PhoneNumber;

                subscription.order             = new OrderType();
                subscription.order.description = "Recurring payment";

                // Create a subscription that is leng of specified occurrences and interval is amount of days ad runs

                subscription.paymentSchedule = new PaymentScheduleType();
                DateTime dtNow = DateTime.UtcNow;
                subscription.paymentSchedule.startDate          = new DateTime(dtNow.Year, dtNow.Month, dtNow.Day);
                subscription.paymentSchedule.startDateSpecified = true;

                subscription.paymentSchedule.totalOccurrences          = Convert.ToInt16(processPaymentRequest.RecurringTotalCycles);
                subscription.paymentSchedule.totalOccurrencesSpecified = true;

                var orderTotal = Math.Round(processPaymentRequest.OrderTotal, 2);
                subscription.amount          = orderTotal;
                subscription.amountSpecified = true;

                // Interval can't be updated once a subscription is created.
                subscription.paymentSchedule.interval = new PaymentScheduleTypeInterval();
                switch (processPaymentRequest.RecurringCyclePeriod)
                {
                case RecurringProductCyclePeriod.Days:
                    subscription.paymentSchedule.interval.length = Convert.ToInt16(processPaymentRequest.RecurringCycleLength);
                    subscription.paymentSchedule.interval.unit   = ARBSubscriptionUnitEnum.days;
                    break;

                case RecurringProductCyclePeriod.Weeks:
                    subscription.paymentSchedule.interval.length = Convert.ToInt16(processPaymentRequest.RecurringCycleLength * 7);
                    subscription.paymentSchedule.interval.unit   = ARBSubscriptionUnitEnum.days;
                    break;

                case RecurringProductCyclePeriod.Months:
                    subscription.paymentSchedule.interval.length = Convert.ToInt16(processPaymentRequest.RecurringCycleLength);
                    subscription.paymentSchedule.interval.unit   = ARBSubscriptionUnitEnum.months;
                    break;

                case RecurringProductCyclePeriod.Years:
                    subscription.paymentSchedule.interval.length = Convert.ToInt16(processPaymentRequest.RecurringCycleLength * 12);
                    subscription.paymentSchedule.interval.unit   = ARBSubscriptionUnitEnum.months;
                    break;

                default:
                    throw new NopException("Not supported cycle period");
                }

                using (var webService = new net.authorize.api.Service())
                {
                    if (_authorizeNetPaymentSettings.UseSandbox)
                    {
                        webService.Url = "https://apitest.authorize.net/soap/v1/Service.asmx";
                    }
                    else
                    {
                        webService.Url = "https://api.authorize.net/soap/v1/Service.asmx";
                    }

                    var authentication = PopulateMerchantAuthentication();
                    var response       = webService.ARBCreateSubscription(authentication, subscription);

                    if (response.resultCode == MessageTypeEnum.Ok)
                    {
                        result.SubscriptionTransactionId      = response.subscriptionId.ToString();
                        result.AuthorizationTransactionCode   = response.resultCode.ToString();
                        result.AuthorizationTransactionResult = string.Format("Approved ({0}: {1})", response.resultCode.ToString(), response.subscriptionId.ToString());

                        if (_authorizeNetPaymentSettings.TransactMode == TransactMode.Authorize)
                        {
                            result.NewPaymentStatus = PaymentStatus.Authorized;
                        }
                        else
                        {
                            result.NewPaymentStatus = PaymentStatus.Paid;
                        }
                    }
                    else
                    {
                        result.AddError(string.Format("Error processing recurring payment. {0}", GetErrors(response)));
                    }
                }
            }

            return(result);
        }
예제 #8
0
        /// <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;

            if (!String.IsNullOrEmpty(this.CardNumber))
            {
                var creditCard = new creditCardType();
                creditCard.cardNumber     = this.CardNumber;
                creditCard.expirationDate = string.Format("{0}-{1}", this.CardExpirationYear, this.CardExpirationMonth);  // required format for API is YYYY-MM
                sub.payment      = new paymentType();
                sub.payment.Item = creditCard;
            }
            else
            {
                throw new InvalidOperationException("Need a credit card number to set up this subscription");
            }

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

            sub.paymentSchedule                    = new paymentScheduleType();
            sub.paymentSchedule.startDate          = this.StartsOn;
            sub.paymentSchedule.startDateSpecified = true;

            sub.paymentSchedule.totalOccurrences          = this.BillingCycles;
            sub.paymentSchedule.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;
            }
            sub.customer       = new customerType();
            sub.customer.email = this.CustomerEmail;
            return(sub);
        }