예제 #1
0
        public void MockARBCancelSubscriptionTest()
        {
            //define all mocked objects as final
            var mockController = GetMockController <ARBCancelSubscriptionRequest, ARBCancelSubscriptionResponse>();
            var mockRequest    = new ARBCancelSubscriptionRequest
            {
                merchantAuthentication = new merchantAuthenticationType {
                    name = "mocktest", Item = "mockKey", ItemElementName = ItemChoiceType.transactionKey
                },
            };
            var mockResponse = new ARBCancelSubscriptionResponse
            {
                refId        = "1234",
                sessionToken = "sessiontoken",
            };

            var errorResponse = new ANetApiResponse();
            var results       = new List <String>();
            const messageTypeEnum messageTypeOk = messageTypeEnum.Ok;

            SetMockControllerExpectations <ARBCancelSubscriptionRequest, ARBCancelSubscriptionResponse, ARBCancelSubscriptionController>(
                mockController.MockObject, mockRequest, mockResponse, errorResponse, results, messageTypeOk);
            mockController.MockObject.Execute(AuthorizeNet.Environment.CUSTOM);
            //mockController.MockObject.Execute();
            // or var controllerResponse = mockController.MockObject.ExecuteWithApiResponse(AuthorizeNet.Environment.CUSTOM);
            var controllerResponse = mockController.MockObject.GetApiResponse();

            Assert.IsNotNull(controllerResponse);

            LogHelper.info(Logger, "ARBCancelSubscription: ");
        }
	    public void MockARBCancelSubscriptionTest()
	    {
		    //define all mocked objects as final
            var mockController = GetMockController<ARBCancelSubscriptionRequest, ARBCancelSubscriptionResponse>();
            var mockRequest = new ARBCancelSubscriptionRequest
                {
                    merchantAuthentication = new merchantAuthenticationType {name = "mocktest", Item = "mockKey", ItemElementName = ItemChoiceType.transactionKey},
                };
            var mockResponse = new ARBCancelSubscriptionResponse
                {
                    refId = "1234",
                    sessionToken = "sessiontoken",
                };

		    var errorResponse = new ANetApiResponse();
		    var results = new List<String>();
            const messageTypeEnum messageTypeOk = messageTypeEnum.Ok;

            SetMockControllerExpectations<ARBCancelSubscriptionRequest, ARBCancelSubscriptionResponse, ARBCancelSubscriptionController>(
                mockController.MockObject, mockRequest, mockResponse, errorResponse, results, messageTypeOk);
            mockController.MockObject.Execute(AuthorizeNet.Environment.CUSTOM);
            //mockController.MockObject.Execute();
            // or var controllerResponse = mockController.MockObject.ExecuteWithApiResponse(AuthorizeNet.Environment.CUSTOM);
            var controllerResponse = mockController.MockObject.GetApiResponse();
            Assert.IsNotNull(controllerResponse);

		    LogHelper.info(Logger, "ARBCancelSubscription: ");
	    }
        public void cancelSub()
        {
            ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment         = AuthorizeNet.Environment.SANDBOX;
            ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = new merchantAuthenticationType()
            {
                name            = ApiLoginID,
                ItemElementName = ItemChoiceType.transactionKey,
                Item            = ApiTransactionKey,
            };

            //Please change the subscriptionId according to your request
            var request = new ARBCancelSubscriptionRequest {
                subscriptionId = CreateSubscription.SubId
            };
            var controller = new ARBCancelSubscriptionController(request);                          // instantiate the contoller that will call the service

            controller.Execute();

            ARBCancelSubscriptionResponse 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)
                {
                    Debug.WriteLine("Success, Subscription Cancelled With RefID : " + response.refId);
                }
            }
            else
            {
                Debug.WriteLine("Error:with cancel " + response.messages.message[0].code + "  " + response.messages.message[0].text);
            }
        }
예제 #4
0
        public static void Run(String ApiLoginID, String ApiTransactionKey)
        {
            Console.WriteLine("Cancel Subscription Sample");

            ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment = AuthorizeNet.Environment.SANDBOX;

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

            //Enter the valid SubscriptionId you want to cancel
            var request = new ARBCancelSubscriptionRequest {
                subscriptionId = "2787902"
            };
            var controller = new ARBCancelSubscriptionController(request);                          // instantiate the contoller that will call the service

            controller.Execute();

            ARBCancelSubscriptionResponse 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 Cancelled With RefID : " + response.refId);
                }
            }
            else
            {
                Console.WriteLine("Error: " + response.messages.message[0].code + "  " + response.messages.message[0].text);
            }
        }
 public static void ARBCancelSubscriptionResponse(ARBCancelSubscriptionResponse argument)
 {
     if (null != argument)
     {
     }
 }
예제 #6
0
        //public static ANetApiResponse Run(String ApiLoginID, String ApiTransactionKey, string subscriptionId)
        //{
        //    Console.WriteLine("Cancel Subscription Sample");

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

        //    //Please change the subscriptionId according to your request
        //    var request = new ARBCancelSubscriptionRequest { subscriptionId = subscriptionId };
        //    var controller = new ARBCancelSubscriptionController(request);                          // instantiate the contoller that will call the service
        //    controller.Execute();

        //    ARBCancelSubscriptionResponse 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 Cancelled With RefID : " + response.refId);
        //        }
        //    }
        //    else if(response != null)
        //    {
        //        Console.WriteLine("Error: " + response.messages.message[0].code + "  " + response.messages.message[0].text);
        //    }

        //    return response;
        //}
        public static void CancelSubscriptionExec(String ApiLoginID, String ApiTransactionKey)
        {
            using (CsvReader csv = new CsvReader(new StreamReader(new FileStream(@"../../../CSV_DATA/CancleASubscription.csv", FileMode.Open)), true))
            {
                Console.WriteLine("Cancel Subscription Sample");
                int      flag       = 0;
                int      fieldCount = csv.FieldCount;
                string[] headers    = csv.GetFieldHeaders();
                //Append Data
                var item1 = DataAppend.ReadPrevData();
                using (CsvFileWriter writer = new CsvFileWriter(new FileStream(@"../../../CSV_DATA/Outputfile.csv", FileMode.Open)))
                {
                    while (csv.ReadNextRecord())
                    {
                        // Create Instance of Customer Api
                        ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment = AuthorizeNET.Environment.SANDBOX;
                        // define the merchant information (authentication / transaction id)
                        ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = new merchantAuthenticationType()
                        {
                            name            = ApiLoginID,
                            ItemElementName = ItemChoiceType.transactionKey,
                            Item            = ApiTransactionKey,
                        };
                        string subscriptionId = null;
                        string TestCase_Id    = null;
                        for (int i = 0; i < fieldCount; i++)
                        {
                            switch (headers[i])
                            {
                            case "subscriptionId":
                                subscriptionId = 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);
                                }
                            }

                            var request = new ARBCancelSubscriptionRequest {
                                subscriptionId = subscriptionId
                            };
                            var controller = new ARBCancelSubscriptionController(request);                          // instantiate the contoller that will call the service
                            controller.Execute();

                            ARBCancelSubscriptionResponse response = controller.GetApiResponse();                   // get the response from the service (errors contained if any)

                            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("CAS_00" + flag.ToString());
                                    row1.Add("CancleASubscription");
                                    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 Cancelled With RefID : " + response.refId);
                                }
                                catch
                                {
                                    CsvRow row1 = new CsvRow();
                                    row1.Add("CAS_00" + flag.ToString());
                                    row1.Add("CancleASubscription");
                                    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("CAS_00" + flag.ToString());
                                row1.Add("CancleASubscription");
                                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("CAS_00" + flag.ToString());
                            row2.Add("CancleASubscription");
                            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
        /// <summary>
        /// Processes the payment.
        /// </summary>
        /// <param name="payment">The payment.</param>
        /// <param name="message">The message.</param>
        /// <returns></returns>
        public override bool ProcessPayment(Payment payment, ref string message)
        {
            string erroneousConfigurationMessage = "Authorize.NET payment gateway is not configured correctly. {0} is not set.";

            // cast the object first
            CreditCardPayment info = (CreditCardPayment)payment;

            if (info == null)
            {
                message = "Payment information is not specified.";
                throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "", message);
            }

            // Check if the gateway is configured correctly
            string processUrl      = String.Empty;
            string user            = String.Empty;
            string password        = String.Empty;
            string recurringMethod = String.Empty;
            string cancelStatus    = String.Empty;

            #region Getting parameters from the db
            // get user name
            if (!Settings.ContainsKey(_UserParameterName) || String.IsNullOrEmpty(Settings[_UserParameterName]))
            {
                message = String.Format(erroneousConfigurationMessage, _UserParameterName);
                throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "", message);
            }

            user = Settings[_UserParameterName];

            // get transaction key
            if (!Settings.ContainsKey(_TransactionKeyParameterName) || String.IsNullOrEmpty(Settings[_TransactionKeyParameterName]))
            {
                message = String.Format(erroneousConfigurationMessage, _TransactionKeyParameterName);
                throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "", message);
            }

            password = Settings[_TransactionKeyParameterName];
            #endregion

            bool processRegularTransaction = true;

            #region --------------- Process Transaction ---------------
            if (payment.Parent != null && (payment.Parent.Parent is PaymentPlan))
            {
                // get recurring method and determine which type of transaction to perform
                if (!Settings.ContainsKey(_RecurringMethodParameterName) || String.IsNullOrEmpty(Settings[_RecurringMethodParameterName]))
                {
                    message = String.Format(erroneousConfigurationMessage, _RecurringMethodParameterName);
                    throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "", message);
                }

                recurringMethod = Settings[_RecurringMethodParameterName];

                if (String.Compare(recurringMethod, _AuthorizeRecurringMethodParameterValue, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    processRegularTransaction = false;
                }
            }

            if (processRegularTransaction)
            {
                #region Get parameters for the regular transaction
                // get processing url
                if (!Settings.ContainsKey(_ProcessUrlParameterName) || String.IsNullOrEmpty(Settings[_ProcessUrlParameterName]))
                {
                    message = String.Format(erroneousConfigurationMessage, _ProcessUrlParameterName);
                    throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "", message);
                }

                processUrl = Settings[_ProcessUrlParameterName];
                #endregion

                #region Process regular transaction

                AuthorizeNetManager mgr = new AuthorizeNetManager(processUrl, user, password);

                TransactionData transData = new TransactionData();
                transData.card = new CreditCard();

                transData.type = Settings[_PaymentOptionParameterName] == "S" ? TransactionType.Sale : TransactionType.Authorization;

                transData.totalAmount = (double)GetSumInUSD(info.Amount, info.Parent.Parent.BillingCurrency);

                transData.card.cardNr  = info.CreditCardNumber;
                transData.card.CSC     = info.CreditCardSecurityCode;
                transData.card.expDate = new DateTime(info.ExpirationYear, info.ExpirationMonth, 1);

                // Find the address
                OrderAddress address = null;
                foreach (OrderAddress a in info.Parent.Parent.OrderAddresses)
                {
                    if (a.Name == info.BillingAddressId)
                    {
                        address = a;
                        break;
                    }
                }

                if (address == null)
                {
                    throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "", "Billing address was not specified.");
                }

                transData.card.customerAddress             = new Authorize.Address();
                transData.card.customerAddress.countryCode = address.CountryCode;
                transData.card.customerAddress.zipCode     = address.PostalCode;
                transData.card.customerAddress.city        = address.City;
                transData.card.customerAddress.state       = address.State;
                transData.card.customerAddress.street      = address.Line1;
                transData.card.customerFirstName           = address.FirstName;
                transData.card.customerLastName            = address.LastName;
                transData.card.customerFax   = address.FaxNumber;
                transData.card.customerPhone = address.DaytimePhoneNumber;
                transData.card.customerEMail = address.Email;

                ResponsePackage pkg = null;

                try
                {
                    pkg = mgr.PerformCardTransaction(transData);
                }
                catch (PaymentException ex)
                {
                    throw;
                    //message = ex.Message;
                    //return false;
                }
                catch
                {
                    throw new PaymentException(PaymentException.ErrorType.ConnectionFailed, "", "Failed to connect to the payment gateway.");
                }

                //info.TextResponse = pkg.responseReasonText;
                info.AuthorizationCode = pkg.responseCode;
                info.ValidationCode    = pkg.approvalCode;
                #endregion
            }
            else
            {
                #region Get parameters for the recurring transaction
                // get processing url
                if (!Settings.ContainsKey(_RecurringProcessUrlParameterName) || String.IsNullOrEmpty(Settings[_RecurringProcessUrlParameterName]))
                {
                    message = String.Format(erroneousConfigurationMessage, _RecurringProcessUrlParameterName);
                    throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "", message);
                }

                processUrl = Settings[_RecurringProcessUrlParameterName];

                // get cancel status
                if (!Settings.ContainsKey(_CancelStatusParameterName) || String.IsNullOrEmpty(Settings[_CancelStatusParameterName]))
                {
                    message = String.Format(erroneousConfigurationMessage, _CancelStatusParameterName);
                    throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "", message);
                }

                cancelStatus = Settings[_CancelStatusParameterName];
                #endregion

                PaymentPlan plan = (PaymentPlan)payment.Parent.Parent;

                #region Process recurring Authorize.NET transaction

                // Payment Plan -> Recurring transaction
                AuthorizeNetRecurringManager recurringMgr = new AuthorizeNetRecurringManager(processUrl, user, password);

                ANetApiResponse response = null;
                try
                {
                    if (String.Compare(plan.Status, cancelStatus, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        // cancel subscription
                        if (!String.IsNullOrEmpty(payment.AuthorizationCode))
                        {
                            ARBCancelSubscriptionResponse cancelResponse = recurringMgr.CancelSubscription(PopulateCancelSubscriptionRequest(info));
                            // clear the authorization code
                            info.AuthorizationCode = String.Empty;
                        }
                        else
                        {
                            throw new PaymentException(PaymentException.ErrorType.ConfigurationError, "Payment AuthorizationCode cannot be null for the CancelSubscription operation", message);
                        }
                    }
                    else if (plan.CompletedCyclesCount == 0)
                    {
                        if (String.IsNullOrEmpty(info.AuthorizationCode))
                        {
                            // create subscription
                            ARBCreateSubscriptionResponse createResponse = recurringMgr.CreateSubscription(PopulateCreateSubscriptionRequest(info));
                            response = (ANetApiResponse)createResponse;
                            info.AuthorizationCode = createResponse.subscriptionId;
                        }
                        else
                        {
                            // update subscription
                            recurringMgr.UpdateSubscription(PopulateUpdateSubscriptionRequest(info));
                        }
                    }
                    else
                    {
                        message = "The operation is invalid.";
                    }
                }
                catch (PaymentException ex)
                {
                    throw ex;
                }
                catch
                {
                    throw new PaymentException(PaymentException.ErrorType.ConnectionFailed, "", "Failed to connect to the payment gateway.");
                }
                #endregion
            }
            #endregion

            return(true);
        }