Example #1
0
    private void SendPayment()
    {
        DataSet ds = customUtility.GetTableData("select * from " + customUtility.DBPrefix + "orderdetail where orderno=(select top 1 orderno from " + customUtility.DBPrefix + "order where userid='" + Session["UserID"] + "' order by orderid desc)");

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

        // define the merchant information (authentication / transaction id)
        ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = new merchantAuthenticationType()
        {
            name            = System.Configuration.ConfigurationManager.AppSettings["paymentLoginID"],
            ItemElementName = ItemChoiceType.transactionKey,
            Item            = System.Configuration.ConfigurationManager.AppSettings["paymentTransID"],
        };

        var creditCard = new creditCardType
        {
            cardNumber     = txtCreditCardNumber.Text,
            expirationDate = cboExpMonth.SelectedItem + cboExpYear.SelectedValue.Substring(cboExpYear.SelectedValue.Length - 2),
            cardCode       = txtCSVNumber.Text
        };

        var name = txtCardHolderName.Text.Split(new char[] { ',', ' ' });

        var billingAddress = new customerAddressType
        {
            firstName = name[0],
            lastName  = name[name.Length - 1],
            address   = Session["streetaddress"].ToString(),
            city      = Session["city"].ToString(),
            state     = Session["state"].ToString(),
            zip       = Session["zipcode"].ToString(),
            country   = Session["country"].ToString()
        };

        var shipToName = Session["shiptoname"].ToString().Split(new char[] { ',', ' ' });

        var shippingAddress = new nameAndAddressType
        {
            firstName = shipToName[0],
            lastName  = shipToName[shipToName.Length - 1],
            address   = Session["shiptostreetaddress"].ToString(),
            city      = Session["shiptocity"].ToString(),
            state     = Session["shiptostate"].ToString(),
            zip       = Session["shiptozipcode"].ToString(),
            country   = Session["shiptocountry"].ToString()
        };

        //standard api call to retrieve response
        var paymentType = new paymentType {
            Item = creditCard
        };

        // Add line Items
        var lineItems = new lineItemType[ds.Tables[0].Rows.Count];

        for (int iCount = 0; iCount < ds.Tables[0].Rows.Count; iCount++)
        {
            lineItems[iCount] = new lineItemType {
                itemId    = (iCount + 1).ToString(),
                name      = ds.Tables[0].Rows[iCount]["ProductName"].ToString(),
                quantity  = Convert.ToDecimal(ds.Tables[0].Rows[iCount]["Qty"]),
                unitPrice = Convert.ToDecimal(ds.Tables[0].Rows[iCount]["price"]),
            };
        }

        var totalAmount        = Convert.ToDecimal(Session["amt"]);
        var transactionRequest = new transactionRequestType
        {
            transactionType = transactionTypeEnum.authCaptureTransaction.ToString(),    // charge the card

            amount    = totalAmount,
            payment   = paymentType,
            billTo    = billingAddress,
            lineItems = lineItems,
            shipTo    = shippingAddress
        };

        var request = new createTransactionRequest {
            transactionRequest = transactionRequest
        };

        // instantiate the controller that will call the service
        var controller = new createTransactionController(request);

        controller.Execute();

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

        // validate response
        if (response != null)
        {
            if (response.messages.resultCode == messageTypeEnum.Ok)
            {
                if (response.transactionResponse.messages != null)
                {
                    lblMessage.Text = "Transction successful!";
                    Response.Redirect("Confirmation.aspx");
                }
                else
                {
                    lblMessage.Text = "Failed Transaction: " + response.transactionResponse.errors[0].errorText;
                }
            }
            else
            {
                if (response.transactionResponse != null && response.transactionResponse.errors != null)
                {
                    lblMessage.Text = "Failed Transaction: " + response.transactionResponse.errors[0].errorText;
                }
                else
                {
                    lblMessage.Text = "Failed Transaction: " + response.messages.message[0].text;
                }
            }
        }
    }
Example #2
0
        public string RunPayment(Order order, ApplicationUser user)
        {
            // Set the environment that we will be running.
            ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment = AuthorizeNet.Environment.SANDBOX;

            // define the merchant information (authentication / transaction id)
            ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication =
                new merchantAuthenticationType()
            {
                name            = "4U4g2Z4FsJSR",
                ItemElementName = ItemChoiceType.transactionKey,
                Item            = "49n6jV6aLrc46RuR",
            };


            // We can either hardcode the CC number, or bring it into the method.
            // Maybe we even want to save it in a secrets file?

            // Maybe create an ENUM that will check against the different CC types and
            // set the cc number based on the enum value
            var creditCard = new creditCardType
            {
                cardNumber     = "4007000000027",
                expirationDate = "0718"
            };

            //This information is something we should be capturing from the user that signed up.
            // It may be a good idea to capture this information in our checkout process, adn save
            // it to our Orders table. We do not have to save addresses to a users profile
            // it is ok for the user to have to manualy put it in everytime.

            customerAddressType billingAddress = GetAddress(order, user);

            //Once we set the payment type...whcih will be CreditCard...
            var paymentType = new paymentType {
                Item = creditCard
            };



            // we need to create a transaction request so that we can eventually charge the card.
            // Note the line items attachment
            var transactionRequest = new transactionRequestType
            {
                transactionType = transactionTypeEnum.authCaptureTransaction.ToString(),
                amount          = order.Total,
                payment         = paymentType,
                billTo          = billingAddress,
                lineItems       = GetLineItems(order.Products),
            };

            var request = new createTransactionRequest {
                transactionRequest = transactionRequest
            };

            // createtransactioncontroller is a controller on the AUth.net side. We need
            // to create a new controller so that we can execute the requrest.
            var controller = new createTransactionController(request);

            controller.Execute();

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

            if (response != null)
            {
                // We should be getting an OK response type.
                if (response.messages.resultCode == messageTypeEnum.Ok)
                {
                    // Notice the different information that we rae receiving back from the trasnaction call.
                    // Should we be saving this information into the database?
                    if (response.transactionResponse.messages != null)
                    {
                        Console.WriteLine("Successfully created transaction with Transaction ID: " +
                                          response.transactionResponse.transId);
                        Console.WriteLine("Response Code: " +
                                          response.transactionResponse.responseCode);
                        Console.WriteLine("Message Code: " +
                                          response.transactionResponse.messages[0].code);
                        Console.WriteLine("Description: " +
                                          response.transactionResponse.messages[0].description);
                        Console.WriteLine("Success, Auth Code : " +
                                          response.transactionResponse.authCode);
                    }
                    else
                    {
                        Console.WriteLine("Failed Transaction.");
                        if (response.transactionResponse.errors != null)
                        {
                            Console.WriteLine("Error Code: " + response.transactionResponse.errors[0].errorCode);
                            Console.WriteLine("Error message: " + response.transactionResponse.errors[0].errorText);
                        }
                    }
                }
                else
                {
                    Console.WriteLine("Failed Transaction.");

                    if (response.transactionResponse != null && response.transactionResponse.errors != null)
                    {
                        Console.WriteLine("Error Code: " + response.transactionResponse.errors[0].errorCode);
                        Console.WriteLine("Error message: " + response.transactionResponse.errors[0].errorText);
                    }
                    else
                    {
                        Console.WriteLine("Error Code: " + response.messages.message[0].code);
                        Console.WriteLine("Error message: " + response.messages.message[0].text);
                    }
                }
            }
            else
            {
                Console.WriteLine("Null Response.");
            }

            return("invalid");
        }
        /// <summary>
        /// Process a payment
        /// </summary>
        /// <param name="processPaymentRequest">Payment info required for an order processing</param>
        /// <returns>Process payment result</returns>
        public ProcessPaymentResult ProcessPayment(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
            };

            transactionTypeEnum transactionType;

            switch (_authorizeNetPaymentSettings.TransactMode)
            {
            case TransactMode.Authorize:
                transactionType = transactionTypeEnum.authOnlyTransaction;
                break;

            case TransactMode.AuthorizeAndCapture:
                transactionType = transactionTypeEnum.authCaptureTransaction;
                break;

            default:
                throw new NopException("Not supported transaction mode");
            }

            var billTo = _authorizeNetPaymentSettings.UseShippingAddressAsBilling && customer.ShippingAddress != null?GetTransactionRequestAddress(customer.ShippingAddress) : GetTransactionRequestAddress(customer.BillingAddress);

            var transactionRequest = new transactionRequestType
            {
                transactionType = transactionType.ToString(),
                amount          = Math.Round(processPaymentRequest.OrderTotal, 2),
                payment         = paymentType,
                currencyCode    = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode,
                billTo          = billTo,
                customerIP      = _webHelper.GetCurrentIpAddress(),
                order           = new orderType
                {
                    //x_invoice_num is 20 chars maximum. hece we also pass x_description
                    invoiceNumber = processPaymentRequest.OrderGuid.ToString().Substring(0, 20),
                    description   = $"Full order #{processPaymentRequest.OrderGuid}"
                }
            };

            if (customer.ShippingAddress != null && !_authorizeNetPaymentSettings.UseShippingAddressAsBilling)
            {
                var shipTo = GetTransactionRequestAddress(customer.ShippingAddress);
                transactionRequest.shipTo = shipTo;
            }

            var request = new createTransactionRequest {
                transactionRequest = transactionRequest
            };

            // instantiate the contoller that will call the service
            var controller = new createTransactionController(request);

            controller.Execute();

            // get the response from the service (errors contained if any)
            var response = GetApiResponse(controller, result.Errors);

            //validate
            if (response == null)
            {
                return(result);
            }

            if (_authorizeNetPaymentSettings.TransactMode == TransactMode.Authorize)
            {
                result.AuthorizationTransactionId   = response.transactionResponse.transId;
                result.AuthorizationTransactionCode =
                    $"{response.transactionResponse.transId},{response.transactionResponse.authCode}";
            }
            if (_authorizeNetPaymentSettings.TransactMode == TransactMode.AuthorizeAndCapture)
            {
                result.CaptureTransactionId =
                    $"{response.transactionResponse.transId},{response.transactionResponse.authCode}";
            }

            result.AuthorizationTransactionResult =
                $"Approved ({response.transactionResponse.responseCode}: {response.transactionResponse.messages[0].description})";
            result.AvsResult        = response.transactionResponse.avsResultCode;
            result.NewPaymentStatus = _authorizeNetPaymentSettings.TransactMode == TransactMode.Authorize ? PaymentStatus.Authorized : PaymentStatus.Paid;

            return(result);
        }
Example #4
0
        /// <summary>
        /// Capture a Transaction Previously Submitted Via CaptureOnly
        /// </summary>
        /// <param name="apiLoginId">Your ApiLoginID</param>
        /// <param name="apiTransactionKey">Your ApiTransactionKey</param>
        /// <param name="transactionAmount">The amount submitted with CaptureOnly</param>
        /// <param name="transactionId">The TransactionID of the previous CaptureOnly operation</param>
        public static void Run(string apiLoginId, string apiTransactionKey, decimal transactionAmount, string transactionId)
        {
            Console.WriteLine("Capture Previously Authorized Amount");

            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
            };

            var creditCard = new creditCardType
            {
                cardNumber     = "4111111111111111",
                expirationDate = "0718"
            };

            //standard api call to retrieve response
            var paymentType = new paymentType {
                Item = creditCard
            };

            var transactionRequest = new transactionRequestType
            {
                transactionType = transactionTypeEnum.priorAuthCaptureTransaction.ToString(),    // capture prior only
                payment         = paymentType,
                amount          = transactionAmount,
                refTransId      = transactionId
            };

            var request = new createTransactionRequest {
                transactionRequest = transactionRequest
            };

            // instantiate the contoller that will call the service
            var controller = new createTransactionController(request);

            controller.Execute();

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

            //validate
            if (response.messages.resultCode == messageTypeEnum.Ok)
            {
                if (response.transactionResponse != null)
                {
                    Console.WriteLine("Success, Auth Code : " + response.transactionResponse.authCode);
                }
            }
            else
            {
                Console.WriteLine("Error: " + response.messages.message[0].code + "  " + response.messages.message[0].text);
                if (response.transactionResponse != null)
                {
                    Console.WriteLine("Transaction Error : " + response.transactionResponse.errors[0].errorCode + " " + response.transactionResponse.errors[0].errorText);
                }
            }
        }
        public void SampleCodeCreateCreditRequestForSettledTransaction()
        {
            Random rnd = new Random(DateTime.Now.Millisecond);


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


            // Find a settled credit card transaction and set txnToCredit to its transaction ID
            string txnToCredit = "Not Set";


            if (txnToCredit == "Not Set")
            {
                Assert.Fail("This test requires that you set txnToCredit to the transaction ID of a settled credit card transaction");
            }


            //get details of the specified transaction
            decimal txnAmount = 0m;
            string  txnCardNo = string.Empty;

            var gtdReq = new getTransactionDetailsRequest {
                transId = txnToCredit
            };
            var gtdCont = new getTransactionDetailsController(gtdReq);

            gtdCont.Execute();
            var gtdResp = gtdCont.GetApiResponse();

            //Test the transaction before continuing
            Assert.AreEqual(messageTypeEnum.Ok, gtdResp.messages.resultCode);

            txnAmount = gtdResp.transaction.settleAmount;
            txnCardNo = ((AuthorizeNet.Api.Contracts.V1.creditCardMaskedType)(gtdResp.transaction.payment.Item)).cardNumber;

            //Create payment type that matches transaction to credit
            var creditCard = new creditCardType {
                cardNumber = txnCardNo.TrimStart(new char[] { 'X' }), expirationDate = "XXXX"
            };
            var paymentType = new paymentType {
                Item = creditCard
            };

            //Create credit request
            transactionRequestType txnType = new transactionRequestType
            {
                amount          = txnAmount,
                refTransId      = txnToCredit,
                transactionType = transactionTypeEnum.refundTransaction.ToString(),
                payment         = paymentType,
            };

            createTransactionRequest creditReq = new createTransactionRequest {
                transactionRequest = txnType
            };
            createTransactionController creditCont = new createTransactionController(creditReq);

            creditCont.Execute();
            createTransactionResponse creditResp = creditCont.GetApiResponse();

            //validate
            Assert.AreEqual("1", creditResp.transactionResponse.messages[0].code);
        }
        public static ANetApiResponse Run(String ApiLoginID, String ApiTransactionKey, decimal amount)
        {
            Console.WriteLine("Charge Credit Card Sample");

            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,
            };

            var creditCard = new creditCardType
            {
                cardNumber     = "4111111111111111",
                expirationDate = "1028",
                cardCode       = "123"
            };

            var billingAddress = new customerAddressType
            {
                firstName = "John",
                lastName  = "Doe",
                address   = "123 My St",
                city      = "OurTown",
                zip       = "98004"
            };

            //standard api call to retrieve response
            var paymentType = new paymentType {
                Item = creditCard
            };

            // Add line Items
            var lineItems = new lineItemType[2];

            lineItems[0] = new lineItemType {
                itemId = "1", name = "t-shirt", quantity = 2, unitPrice = new Decimal(15.00)
            };
            lineItems[1] = new lineItemType {
                itemId = "2", name = "snowboard", quantity = 1, unitPrice = new Decimal(450.00)
            };

            var transactionRequest = new transactionRequestType
            {
                transactionType = transactionTypeEnum.authCaptureTransaction.ToString(),    // charge the card

                amount    = amount,
                payment   = paymentType,
                billTo    = billingAddress,
                lineItems = lineItems
            };

            var request = new createTransactionRequest {
                transactionRequest = transactionRequest
            };

            // instantiate the controller that will call the service
            var controller = new createTransactionController(request);

            controller.Execute();

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

            // validate response
            if (response != null)
            {
                if (response.messages.resultCode == messageTypeEnum.Ok)
                {
                    if (response.transactionResponse.messages != null)
                    {
                        Console.WriteLine("Successfully created transaction with Transaction ID: " + response.transactionResponse.transId);
                        Console.WriteLine("Response Code: " + response.transactionResponse.responseCode);
                        Console.WriteLine("Message Code: " + response.transactionResponse.messages[0].code);
                        Console.WriteLine("Description: " + response.transactionResponse.messages[0].description);
                        Console.WriteLine("Success, Auth Code : " + response.transactionResponse.authCode);
                    }
                    else
                    {
                        Console.WriteLine("Failed Transaction.");
                        if (response.transactionResponse.errors != null)
                        {
                            Console.WriteLine("Error Code: " + response.transactionResponse.errors[0].errorCode);
                            Console.WriteLine("Error message: " + response.transactionResponse.errors[0].errorText);
                        }
                    }
                }
                else
                {
                    Console.WriteLine("Failed Transaction.");
                    if (response.transactionResponse != null && response.transactionResponse.errors != null)
                    {
                        Console.WriteLine("Error Code: " + response.transactionResponse.errors[0].errorCode);
                        Console.WriteLine("Error message: " + response.transactionResponse.errors[0].errorText);
                    }
                    else
                    {
                        Console.WriteLine("Error Code: " + response.messages.message[0].code);
                        Console.WriteLine("Error message: " + response.messages.message[0].text);
                    }
                }
            }
            else
            {
                Console.WriteLine("Null Response.");
            }

            return(response);
        }
Example #7
0
        public ActionableResponse AfterCalculation(CalculationRequest request, CalculationResponse response)
        {
            var name       = request.Inputs.FirstOrDefault(x => x.Ref == "iName");
            var lastName   = request.Inputs.FirstOrDefault(x => x.Ref == "iSurname");
            var cardNumber = request.Inputs.FirstOrDefault(x => x.Ref == "iCardNumber");
            var year       = request.Inputs.FirstOrDefault(x => x.Ref == "iYear");
            var month      = request.Inputs.FirstOrDefault(x => x.Ref == "iMonth");
            var cvc        = request.Inputs.FirstOrDefault(x => x.Ref == "iCVC");
            var amount     = Convert.ToDecimal(request.Inputs.FirstOrDefault(x => x.Ref == "iAmount").Value[0][0].Value);
            var address    = request.Inputs.FirstOrDefault(x => x.Ref == "iAddress");
            var city       = request.Inputs.FirstOrDefault(x => x.Ref == "iCity");
            var zip        = request.Inputs.FirstOrDefault(x => x.Ref == "iZip");

            var errRespo = new ActionableResponse();

            errRespo.Success        = false;
            errRespo.ResponseAction = ResponseAction.Cancel;
            errRespo.Messages       = new System.Collections.Generic.List <string>();

            try
            {
                ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment         = AuthorizeNet.Environment.SANDBOX;
                ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = new merchantAuthenticationType()
                {
                    name            = apiLoginId,
                    ItemElementName = ItemChoiceType.transactionKey,
                    Item            = transactionKey,
                };
                var creditCard = new creditCardType
                {
                    cardNumber     = cardNumber.Value[0][0].Value,
                    expirationDate = month.Value[0][0].Value + year.Value[0][0].Value,
                    cardCode       = cvc.Value[0][0].Value
                };
                var billingAddress = new customerAddressType
                {
                    firstName = name.Value[0][0].Value,
                    lastName  = lastName.Value[0][0].Value,
                    address   = address.Value[0][0].Value,
                    city      = city.Value[0][0].Value,
                    zip       = zip.Value[0][0].Value
                };
                var paymentType = new paymentType {
                    Item = creditCard
                };

                // Add line Items
                var lineItems = new lineItemType[2];
                lineItems[0] = new lineItemType {
                    itemId = "1", name = "t-shirt", quantity = 2, unitPrice = new Decimal(15.00)
                };
                lineItems[1] = new lineItemType {
                    itemId = "2", name = "snowboard", quantity = 1, unitPrice = new Decimal(450.00)
                };
                var transactionRequest = new transactionRequestType
                {
                    transactionType = transactionTypeEnum.authCaptureTransaction.ToString(),    // charge the card

                    amount    = amount,
                    payment   = paymentType,
                    billTo    = billingAddress,
                    lineItems = lineItems
                };

                var req = new createTransactionRequest {
                    transactionRequest = transactionRequest
                };
                var controller = new createTransactionController(req);
                controller.Execute();

                var resp = controller.GetApiResponse();
                if (resp != null)
                {
                    if (resp.messages.resultCode == messageTypeEnum.Ok)
                    {
                        if (resp.transactionResponse.messages != null)
                        {
                            response.Outputs.FirstOrDefault(x => x.Ref == "oResponse").Value[0][0].Value
                                = "Successfully created transaction with Transaction ID: " + resp.transactionResponse.transId
                                  + "<br />" + "Response Code: " + resp.transactionResponse.responseCode
                                  + "<br />" + "Message Code: " + resp.transactionResponse.messages[0].code
                                  + "<br />" + "Description: " + resp.transactionResponse.messages[0].description
                                  + "<br />" + "Success, Auth Code : " + resp.transactionResponse.authCode;

                            return(new ActionableResponse
                            {
                                Success = true
                            });
                        }
                        else
                        {
                            errRespo.Messages.Add("Failed Transaction.");

                            if (resp.transactionResponse.errors != null)
                            {
                                errRespo.Messages.Add("Error Code: " + resp.transactionResponse.errors[0].errorCode);
                                errRespo.Messages.Add("Error message: " + resp.transactionResponse.errors[0].errorText);
                            }
                            return(errRespo);
                        }
                    }
                    else
                    {
                        errRespo.Messages.Add("Failed Transaction.");

                        if (resp.transactionResponse != null && resp.transactionResponse.errors != null)
                        {
                            errRespo.Messages.Add("Error Code: " + resp.transactionResponse.errors[0].errorCode);
                            errRespo.Messages.Add("Error message: " + resp.transactionResponse.errors[0].errorText);
                        }
                        else
                        {
                            errRespo.Messages.Add("Error Code: " + resp.messages.message[0].code);
                            errRespo.Messages.Add("Error message: " + resp.messages.message[0].text);
                        }
                        return(errRespo);
                    }
                }
                else
                {
                    errRespo.Messages.Add("Null Response.");
                }
                return(errRespo);
            }
            catch (Exception ex)
            {
                return(new ActionableResponse
                {
                    Success = false,
                    Messages = new System.Collections.Generic.List <string>()
                    {
                        ex.Message
                    },
                    ResponseAction = ResponseAction.Cancel
                });
            }
        }
        //private string authorizeNetUrl = "https://apitest.authorize.net/xml/v1/request.api";
        //private string authorizeNetUrl = "https://api.authorize.net/xml/v1/request.api";

        public createTransactionResponse RunCharge(String ApiLoginID, String ApiTransactionKey, creditCardType creditCard, customerAddressType billingAddress, lineItemType[] lineItems, decimal amount)
        {
            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,
            };

            //standard api call to retrieve response
            var paymentType = new paymentType {
                Item = creditCard
            };

            var transactionRequest = new transactionRequestType
            {
                transactionType = transactionTypeEnum.authCaptureTransaction.ToString(),        // charge the card

                amount    = amount,
                payment   = paymentType,
                billTo    = billingAddress,
                lineItems = lineItems
            };

            var request = new createTransactionRequest {
                transactionRequest = transactionRequest
            };

            // instantiate the controller that will call the service
            var controller = new createTransactionController(request);

            controller.Execute();

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

            // validate response
            if (response != null)
            {
                return(response);
            }
            else
            {
                return(null);
            }
        }
        public string Run()
        {
            // controllers.Base for authoriseNet
            ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment = AuthorizeNet.Environment.SANDBOX;

            ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = new merchantAuthenticationType()
            {
                name            = _config["AN-ApiLoginID"],
                ItemElementName = ItemChoiceType.transactionKey,
                Item            = _config["AN-TransactionKey"]
            };

            // set a credit card.
            // can be hard coded. or brought in through secrets

            // DO NOT ask the user for their credit number

            var creditCard = new creditCardType
            {
                cardNumber = "4111111111111111",
                cardCode   = "1021"
            };

            customerAddressType billingAddress = GetAddress("someUserId");

            var paymentType = new paymentType {
                Item = creditCard
            };

            // this class takes everything we've defined, and puts it all in one object.
            var potato = new transactionRequestType
            {
                transactionType = transactionTypeEnum.authCaptureTransaction.ToString(),
                amount          = 122.5m,
                payment         = paymentType,
                billTo          = billingAddress
            };

            var request = new createTransactionRequest {
                transactionRequest = potato
            };

            var controller = new createTransactionController(request);

            // This is going to produce an error!
            // to fix this error........
            // PM> install-package System.Configuration.ConfigurationManager
            controller.Execute();

            var response = controller.GetApiResponse();

            if (response != null)
            {
                if (response.messages.resultCode == messageTypeEnum.Ok)
                {
                    return("success!");
                }
            }

            return("fail");
        }
        public ActionResult Checkout(string cardNumber, DateTime expirationDate, string cardCode,
                                     string firstName, string lastName, string address, string city, string zip)
        {
            #region cc

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

            // define the merchant information (authentication / transaction id)
            ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = new merchantAuthenticationType()
            {
                name            = "5m9JuX5a",
                ItemElementName = ItemChoiceType.transactionKey,
                Item            = "3uA3H8968GjC69f7",
            };

            var creditCard = new creditCardType
            {
                cardNumber     = cardNumber,
                expirationDate = expirationDate.ToString("MMyy"),
                cardCode       = cardCode
            };

            var billingAddress = new customerAddressType
            {
                firstName = firstName,
                lastName  = lastName,
                address   = address,
                city      = city,
                zip       = zip
            };

            //standard api call to retrieve response
            var paymentType = new paymentType {
                Item = creditCard
            };

            // Add line Items

            var cart = BL.Cart.Get();

            var lineItems = new lineItemType[cart.Items.Count];

            decimal amount = 0.0M;

            for (int i = 0; i < cart.Items.Count; i++)
            {
                lineItems[i] = new lineItemType
                {
                    itemId    = cart.Items[i].Product.Id.ToString(),
                    name      = cart.Items[i].Product.Name,
                    quantity  = cart.Items[i].Quantity,
                    unitPrice = new Decimal(cart.Items[i].Product.Price.Value)
                };

                amount += Convert.ToDecimal(cart.Items[i].Product.Price.Value);
            }

            var transactionRequest = new transactionRequestType
            {
                transactionType = transactionTypeEnum.authCaptureTransaction.ToString(),    // charge the card

                amount    = amount,
                payment   = paymentType,
                billTo    = billingAddress,
                lineItems = lineItems
            };

            var request = new createTransactionRequest {
                transactionRequest = transactionRequest
            };

            // instantiate the controller that will call the service
            var controller = new createTransactionController(request);
            controller.Execute();

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

            // validate response
            if (response != null)
            {
                if (response.messages.resultCode == messageTypeEnum.Ok)
                {
                    if (response.transactionResponse.messages != null)
                    {
                        Console.WriteLine("Successfully created transaction with Transaction ID: " + response.transactionResponse.transId);
                        Console.WriteLine("Response Code: " + response.transactionResponse.responseCode);
                        Console.WriteLine("Message Code: " + response.transactionResponse.messages[0].code);
                        Console.WriteLine("Description: " + response.transactionResponse.messages[0].description);
                        Console.WriteLine("Success, Auth Code : " + response.transactionResponse.authCode);

                        var db = new ShoppingCartEntities();

                        Order order = new Order();
                        order.CustomerId   = Convert.ToInt32(Session["id"]);
                        order.OrderDate    = DateTime.Now;
                        order.OrderStatus  = 1; //1 shayad pending hay
                        order.OrderDetails = new List <OrderDetail>();

                        foreach (var item in cart.Items)
                        {
                            order.OrderDetails.Add(new OrderDetail()
                            {
                                Amount    = item.Product.Price,
                                Quantity  = item.Quantity,
                                ProductId = item.Product.Id
                            });
                        }
                        db.Orders.Add(order);
                        db.SaveChanges();

                        return(RedirectToAction("Index", "Home"));
                    }
                    else
                    {
                        Console.WriteLine("Failed Transaction.");
                        if (response.transactionResponse.errors != null)
                        {
                            // Console.WriteLine("Error Code: " + response.transactionResponse.errors[0].errorCode);
                            Console.WriteLine("Error message: " + response.transactionResponse.errors[0].errorText);

                            ViewBag.error = response.transactionResponse.errors[0].errorText;
                        }
                    }
                }
                else
                {
                    Console.WriteLine("Failed Transaction.");
                    if (response.transactionResponse != null && response.transactionResponse.errors != null)
                    {
                        // Console.WriteLine("Error Code: " + response.transactionResponse.errors[0].errorCode);
                        Console.WriteLine("Error message: " + response.transactionResponse.errors[0].errorText);
                        ViewBag.error = response.transactionResponse.errors[0].errorText;
                    }
                    else
                    {
                        // Console.WriteLine("Error Code: " + response.messages.message[0].code);
                        Console.WriteLine("Error message: " + response.messages.message[0].text);
                        ViewBag.error = response.messages.message[0].text;
                    }
                }
            }
            else
            {
                Console.WriteLine("Null Response.");
                ViewBag.error = "Null response";
            }


            #endregion



            return(View());
        }
Example #11
0
        public static ANetApiResponse Run(string ApiLoginID, string ApiTransactionKey, string emailId)
        {
            Console.WriteLine("CreateCustomerProfile Sample");

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


            var creditCard = new creditCardType
            {
                cardNumber     = "4111111111111111",
                expirationDate = "0718"
            };

            var bankAccount = new bankAccountType
            {
                accountNumber = "231323342",
                routingNumber = "000000224",
                accountType   = bankAccountTypeEnum.checking,
                echeckType    = echeckTypeEnum.WEB,
                nameOnAccount = "test",
                bankName      = "Bank Of America"
            };

            //standard api call to retrieve response
            paymentType cc = new paymentType {
                Item = creditCard
            };
            paymentType echeck = new paymentType {
                Item = bankAccount
            };

            List <customerPaymentProfileType> paymentProfileList = new List <customerPaymentProfileType>();
            customerPaymentProfileType        ccPaymentProfile   = new customerPaymentProfileType();

            ccPaymentProfile.payment = cc;

            customerPaymentProfileType echeckPaymentProfile = new customerPaymentProfileType();

            echeckPaymentProfile.payment = echeck;

            paymentProfileList.Add(ccPaymentProfile);
            paymentProfileList.Add(echeckPaymentProfile);

            List <customerAddressType> addressInfoList = new List <customerAddressType>();
            customerAddressType        homeAddress     = new customerAddressType();

            homeAddress.address = "10900 NE 8th St";
            homeAddress.city    = "Seattle";
            homeAddress.zip     = "98006";


            customerAddressType officeAddress = new customerAddressType();

            officeAddress.address = "1200 148th AVE NE";
            officeAddress.city    = "NorthBend";
            officeAddress.zip     = "92101";

            addressInfoList.Add(homeAddress);
            addressInfoList.Add(officeAddress);


            customerProfileType customerProfile = new customerProfileType();

            customerProfile.merchantCustomerId = "Test CustomerID";
            customerProfile.email           = emailId;
            customerProfile.paymentProfiles = paymentProfileList.ToArray();
            customerProfile.shipToList      = addressInfoList.ToArray();

            var request = new createCustomerProfileRequest {
                profile = customerProfile, validationMode = validationModeEnum.none
            };

            var controller = new createCustomerProfileController(request);          // instantiate the contoller that will call the service

            controller.Execute();

            createCustomerProfileResponse 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, CustomerProfileID : " + response.customerProfileId);
                    Console.WriteLine("Success, CustomerPaymentProfileID : " + response.customerPaymentProfileIdList[0]);
                    Console.WriteLine("Success, CustomerShippingProfileID : " + response.customerShippingAddressIdList[0]);
                }
            }
            else if (response != null)
            {
                Console.WriteLine("Error: " + response.messages.message[0].code + "  " + response.messages.message[0].text);
            }

            return(response);
        }
Example #12
0
        //private string authorizeNetUrl = "https://apitest.authorize.net/xml/v1/request.api";
        //private string authorizeNetUrl = "https://api.authorize.net/xml/v1/request.api";
        //NOTE: cardCode not a required element of creditCardType for a refund, and only last four numbers of cardNumber needeed

        public createTransactionResponse RunRefund(String ApiLoginID, String ApiTransactionKey, creditCardType creditCard, decimal TransactionAmount, string TransactionID)
        {
            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
            };


            //standard api call to retrieve response
            var paymentType = new paymentType {
                Item = creditCard
            };

            var transactionRequest = new transactionRequestType
            {
                transactionType = transactionTypeEnum.refundTransaction.ToString(),        // refund type
                payment         = paymentType,
                amount          = TransactionAmount,
                refTransId      = TransactionID
            };

            var request = new createTransactionRequest {
                transactionRequest = transactionRequest
            };

            // instantiate the controller that will call the service
            var controller = new createTransactionController(request);

            controller.Execute();

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

            // validate response
            if (response != null)
            {
                return(response);
            }
            else
            {
                return(null);
            }
        }
Example #13
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);
        }
        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 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);
        }
Example #15
0
        public string Run(ApplicationUser user, Order order)
        {
            ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment         = AuthorizeNet.Environment.SANDBOX;
            ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = new merchantAuthenticationType
            {
                name            = _configuration["AuthorizeNet:LoginID"],
                ItemElementName = ItemChoiceType.transactionKey,
                Item            = _configuration["AuthorizeNet:TransactionKey"]
            };

            long number = (long)order.CardNumber;

            creditCardType creditCard = new creditCardType
            {
                cardNumber     = number.ToString(),
                expirationDate = "1219"
            };

            customerAddressType address = new customerAddressType
            {
                firstName = user.FirstName,
                lastName  = user.LastName,
                address   = order.ShippingAddress,
                city      = order.City,
                zip       = order.Zip
            };

            paymentType payment = new paymentType {
                Item = creditCard
            };

            transactionRequestType transactionRequest = new transactionRequestType
            {
                transactionType = transactionTypeEnum.authCaptureTransaction.ToString(),
                amount          = order.TotalPrice,
                payment         = payment,
                billTo          = address,
            };

            createTransactionRequest request = new createTransactionRequest
            {
                transactionRequest = transactionRequest
            };

            createTransactionController controller = new createTransactionController(request);

            controller.Execute();

            createTransactionResponse response = controller.GetApiResponse();
            StringBuilder             logText  = new StringBuilder();

            if (response != null)
            {
                if (response.messages.resultCode == messageTypeEnum.Ok)
                {
                    if (response.transactionResponse.messages != null)
                    {
                        logText.AppendLine($"Successfully created transaction (ID: {response.transactionResponse.transId})");
                        logText.AppendLine($"Response Code: {response.transactionResponse.responseCode}");
                        logText.AppendLine($"Message Code: {response.transactionResponse.messages[0].code}");
                        logText.AppendLine($"Description: {response.transactionResponse.messages[0].description}");
                        logText.AppendLine($"Auth Code: {response.transactionResponse.authCode}");
                    }
                    else
                    {
                        if (response.transactionResponse.errors != null)
                        {
                            logText.AppendLine("Failed Transaction.");
                            logText.AppendLine($"Error Code: {response.transactionResponse.errors[0].errorCode}");
                            logText.AppendLine($"Error Message: {response.transactionResponse.errors[0].errorText}");
                        }
                    }
                }
                else
                {
                    logText.AppendLine("Failed Transaction.");
                    if (response.transactionResponse != null && response.transactionResponse.errors != null)
                    {
                        logText.AppendLine($"Error Code: {response.transactionResponse.errors[0].errorCode}");
                        logText.AppendLine($"Error Message: {response.transactionResponse.errors[0].errorText}");
                    }
                    else
                    {
                        logText.AppendLine($"Error Code: {response.messages.message[0].code}");
                        logText.AppendLine($"Error Message: {response.messages.message[0].text}");
                    }
                }
            }
            else
            {
                logText.AppendLine("Transaction request resulted in null response");
            }
            return(logText.ToString());
        }
Example #16
0
        public static AuthorizeNetResponse ExecutePayment(Order newOrder, creditCardType creditCardInfo)
        {
            ConfigureAuthorizeNetAPI();

            AuthorizeNetResponse authorizeNetResponse = new AuthorizeNetResponse();

            try
            {
                var billingAddress = new customerAddressType
                {
                    firstName   = newOrder.CustomerName,
                    email       = newOrder.CustomerEmail,
                    phoneNumber = newOrder.CustomerPhone,
                    country     = newOrder.CustomerCountry,
                    city        = newOrder.CustomerCity,
                    address     = newOrder.CustomerAddress,
                    zip         = newOrder.CustomerZipCode
                };

                //standard api call to retrieve response
                var paymentType = new paymentType {
                    Item = creditCardInfo
                };


                var lineItems = new lineItemType[newOrder.OrderItems.Count];
                var i         = 0;
                foreach (var orderItem in newOrder.OrderItems)
                {
                    lineItems[i] = new lineItemType {
                        itemId = orderItem.ProductID.ToString(), name = orderItem.ProductName.ToAuthorizeNetProductName(), quantity = orderItem.Quantity, unitPrice = orderItem.ItemPrice
                    };

                    i++;
                }

                var transactionRequest = new transactionRequestType
                {
                    transactionType = transactionTypeEnum.authCaptureTransaction.ToString(),    // charge the card

                    amount    = newOrder.FinalAmmount,
                    payment   = paymentType,
                    billTo    = billingAddress,
                    shipTo    = billingAddress,
                    lineItems = lineItems,
                };

                var request = new createTransactionRequest {
                    transactionRequest = transactionRequest
                };

                // instantiate the controller that will call the service
                var controller = new createTransactionController(request);
                controller.Execute();

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

                // validate response
                if (authorizeNetResponse.Response != null)
                {
                    if (authorizeNetResponse.Response.messages.resultCode == messageTypeEnum.Ok)
                    {
                        if (authorizeNetResponse.Response.transactionResponse.messages != null)
                        {
                            authorizeNetResponse.Success  = true;
                            authorizeNetResponse.Message  = string.Format("Transaction Successfull.{0}Transaction ID is {1}", Environment.NewLine, authorizeNetResponse.Response.transactionResponse.transId);
                            authorizeNetResponse.Response = authorizeNetResponse.Response;
                        }
                        else
                        {
                            authorizeNetResponse.Success  = false;
                            authorizeNetResponse.Message  = string.Format("Transaction Failed.{0}{1}", Environment.NewLine, string.Join(Environment.NewLine, authorizeNetResponse.Response.transactionResponse.errors.Select(x => string.Format("Error: {0}~{1}", x.errorCode, x.errorText)).ToList()));
                            authorizeNetResponse.Response = authorizeNetResponse.Response;
                        }
                    }
                    else
                    {
                        authorizeNetResponse.Success = false;

                        if (authorizeNetResponse.Response.transactionResponse != null && authorizeNetResponse.Response.transactionResponse.errors != null)
                        {
                            authorizeNetResponse.Message = string.Format("Transaction Failed.{0}{1}", Environment.NewLine, string.Join(Environment.NewLine, authorizeNetResponse.Response.transactionResponse.errors.Select(x => string.Format("Error: {0}~{1}", x.errorCode, x.errorText)).ToList()));
                        }
                        else
                        {
                            authorizeNetResponse.Message = string.Format("Transaction Failed.{0}{1}", Environment.NewLine, string.Join(Environment.NewLine, authorizeNetResponse.Response.messages.message.Select(x => string.Format("Error: {0}~{1}", x.code, x.text)).ToList()));
                        }

                        authorizeNetResponse.Response = authorizeNetResponse.Response;
                    }
                }
                else
                {
                    authorizeNetResponse.Success  = false;
                    authorizeNetResponse.Message  = "No valid response from Authorize.Net.";
                    authorizeNetResponse.Response = authorizeNetResponse.Response;
                }
            }
            catch (Exception ex)
            {
                authorizeNetResponse.Success = false;
                authorizeNetResponse.Message = string.Format("Error occured on server. {0}", ex.Message);
            }

            return(authorizeNetResponse);
        }
Example #17
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 void ChargeCC(SubscriptionModel cCnumber)
        {
            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,
            };

            var creditCard = new creditCardType
            {
                cardNumber     = cCnumber.CardNumber,
                expirationDate = cCnumber.Expiration,
                cardCode       = cCnumber.CVV
            };

            //standard api call to retrieve response
            var paymentType = new paymentType {
                Item = creditCard
            };

            var transactionRequest = new transactionRequestType
            {
                transactionType = transactionTypeEnum.authCaptureTransaction.ToString(),    // charge the card
                amount          = 133.45m,
                payment         = paymentType
            };

            var request = new createTransactionRequest {
                transactionRequest = transactionRequest
            };

            // instantiate the contoller that will call the service
            var controller = new createTransactionController(request);

            controller.Execute();

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

            iDcode = response.transactionResponse.authCode;

            if (response.messages.resultCode == messageTypeEnum.Ok)
            {
                if (response.transactionResponse != null)
                {
                    Debug.WriteLine("Success, Auth Code Charge : " + response.transactionResponse.authCode);
                }
            }
            else
            {
                Console.WriteLine("Error: " + response.messages.message[0].code + "  " + response.messages.message[0].text);
                if (response.transactionResponse != null)
                {
                    Debug.WriteLine("Transaction Error Charge: " + response.transactionResponse.errors[0].errorCode + " " + response.transactionResponse.errors[0].errorText);
                }
            }
        }
Example #19
0
        public static void Run(String ApiLoginID, String ApiTransactionKey)
        {
            Console.WriteLine("Charge Credit Card Sample");

            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,
            };

            var creditCard = new creditCardType
            {
                cardNumber     = "4111111111111111",
                expirationDate = "0718",
                cardCode       = "123"
            };

            //standard api call to retrieve response
            var paymentType = new paymentType {
                Item = creditCard
            };

            // Add line Items
            var lineItems = new lineItemType[2];

            lineItems[0] = new lineItemType {
                itemId = "1", name = "t-shirt", quantity = 2, unitPrice = new Decimal(15.00)
            };
            lineItems[1] = new lineItemType {
                itemId = "2", name = "snowboard", quantity = 1, unitPrice = new Decimal(450.00)
            };

            var transactionRequest = new transactionRequestType
            {
                transactionType = transactionTypeEnum.authCaptureTransaction.ToString(),    // charge the card
                amount          = 133.45m,
                payment         = paymentType,
                lineItems       = lineItems
            };

            var request = new createTransactionRequest {
                transactionRequest = transactionRequest
            };

            // instantiate the contoller that will call the service
            var controller = new createTransactionController(request);

            controller.Execute();

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

            if (response.messages.resultCode == messageTypeEnum.Ok)
            {
                if (response.transactionResponse != null)
                {
                    Console.WriteLine("Success, Auth Code : " + response.transactionResponse.authCode);
                }
            }
            else
            {
                Console.WriteLine("Error: " + response.messages.message[0].code + "  " + response.messages.message[0].text);
                if (response.transactionResponse != null)
                {
                    Console.WriteLine("Transaction Error : " + response.transactionResponse.errors[0].errorCode + " " + response.transactionResponse.errors[0].errorText);
                }
            }
        }
        public void SampleCodeCreateTransactionPriorAuthCapture()
        {
            //Common code to set for all requests
            ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = CustomMerchantAuthenticationType;
            ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment         = TestEnvironment;

            //set up data based on transaction
            var transactionAmount = SetValidTransactionAmount(Counter);
            var creditCard        = new creditCardType {
                cardNumber = "4111111111111111", expirationDate = "0622"
            };

            //Build auth only transaction request.
            var paymentType = new paymentType {
                Item = creditCard
            };
            var transactionRequest = new transactionRequestType
            {
                transactionType = transactionTypeEnum.authOnlyTransaction.ToString(),
                payment         = paymentType,
                amount          = transactionAmount,
            };
            var request = new createTransactionRequest {
                transactionRequest = transactionRequest
            };
            var controller = new createTransactionController(request);

            controller.Execute();
            var response = controller.GetApiResponse();


            //Get transaction details
            var getDetailsReq = new getTransactionDetailsRequest
            {
                transId = response.transactionResponse.transId
            };
            var getDetailsCont = new getTransactionDetailsController(getDetailsReq);

            getDetailsCont.Execute();
            var getDetailsResp = getDetailsCont.GetApiResponse();


            //Build and execute the capture request.
            var capCC = new creditCardType
            {
                cardNumber     = ((creditCardMaskedType)(getDetailsResp.transaction.payment.Item)).cardNumber.TrimStart(new char[] { 'X' }),
                expirationDate = "XXXX",
            };

            var capPayment = new paymentType {
                Item = capCC
            };

            var capTransactionRequest = new transactionRequestType
            {
                transactionType = transactionTypeEnum.priorAuthCaptureTransaction.ToString(),
                refTransId      = getDetailsResp.transaction.transId,
                authCode        = getDetailsResp.transaction.authCode,
            };

            request = new createTransactionRequest {
                transactionRequest = capTransactionRequest
            };
            controller = new createTransactionController(request);
            controller.Execute();
            var capResponse = controller.GetApiResponse();

            //validate
            Assert.AreEqual("1", capResponse.transactionResponse.messages[0].code);
        }
Example #21
0
        //  public static ANetApiResponse Run(String ApiLoginID, String ApiTransactionKey)
        //  {
        //      Console.WriteLine("Charge Tokenized Credit Card Sample");

        //      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,
        //      };

        //      var creditCard = new creditCardType
        //      {
        //          cardNumber = "4111111111111111",
        //          expirationDate = "0718",
        //          cryptogram = Guid.NewGuid().ToString()             // Set this to the value of the cryptogram received from the token provide
        //      };

        //      //standard api call to retrieve response
        //      var paymentType = new paymentType { Item = creditCard };

        //      var transactionRequest = new transactionRequestType
        //      {
        //          transactionType = transactionTypeEnum.authCaptureTransaction.ToString(),    // charge the card
        //          amount = 133.45m,
        //          payment = paymentType
        //      };

        //      var request = new createTransactionRequest { transactionRequest = transactionRequest };

        //      // instantiate the contoller that will call the service
        //      var controller = new createTransactionController(request);
        //      controller.Execute();

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

        //      //validate
        //      if (response != null)
        //      {
        //          if (response.messages.resultCode == messageTypeEnum.Ok)
        //          {
        //              if(response.transactionResponse.messages != null)
        //              {
        //                  Console.WriteLine("Successfully created transaction with Transaction ID: " + response.transactionResponse.transId);
        //                  Console.WriteLine("Response Code: " + response.transactionResponse.responseCode);
        //                  Console.WriteLine("Message Code: " + response.transactionResponse.messages[0].code);
        //                  Console.WriteLine("Description: " + response.transactionResponse.messages[0].description);
        //Console.WriteLine("Success, Auth Code : " + response.transactionResponse.authCode);
        //              }
        //              else
        //              {
        //                  Console.WriteLine("Failed Transaction.");
        //                  if (response.transactionResponse.errors != null)
        //                  {
        //                      Console.WriteLine("Error Code: " + response.transactionResponse.errors[0].errorCode);
        //                      Console.WriteLine("Error message: " + response.transactionResponse.errors[0].errorText);
        //                  }
        //              }
        //          }
        //          else
        //          {
        //              Console.WriteLine("Failed Transaction.");
        //              if (response.transactionResponse != null && response.transactionResponse.errors != null)
        //              {
        //                  Console.WriteLine("Error Code: " + response.transactionResponse.errors[0].errorCode);
        //                  Console.WriteLine("Error message: " + response.transactionResponse.errors[0].errorText);
        //              }
        //              else
        //              {
        //                  Console.WriteLine("Error Code: " + response.messages.message[0].code);
        //                  Console.WriteLine("Error message: " + response.messages.message[0].text);
        //              }
        //          }
        //      }
        //      else
        //      {
        //          Console.WriteLine("Null Response.");
        //      }

        //      return response;
        //  }

        public static void ChargeTokenizedCreditCardExec(String ApiLoginID, String ApiTransactionKey)
        {
            using (CsvReader csv = new CsvReader(new StreamReader(new FileStream(@"../../../CSV_DATA/ChargeTokenizedCreditCard.csv", FileMode.Open)), true))
            {
                Console.WriteLine("Charge Tokenized Credit Card 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())
                    {
                        ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment = AuthorizeNET.Environment.SANDBOX;



                        var creditCard = new creditCardType
                        {
                            cardNumber     = "4111111111111111",
                            expirationDate = "0718",
                            cryptogram     = Guid.NewGuid().ToString()         // Set this to the value of the cryptogram received from the token provide
                        };

                        //standard api call to retrieve response
                        var paymentType = new paymentType {
                            Item = creditCard
                        };

                        var transactionRequest = new transactionRequestType
                        {
                            transactionType = transactionTypeEnum.authCaptureTransaction.ToString(),    // charge the card
                            amount          = 133.45m,
                            payment         = paymentType
                        };

                        string apiLogin       = null;
                        string transactionKey = null;
                        string TestCaseId     = null;
                        for (int i = 0; i < fieldCount; i++)
                        {
                            switch (headers[i])
                            {
                            case "TestCaseId":
                                TestCaseId = csv[i];
                                break;

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

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

                            default:
                                break;
                            }
                        }
                        // define the merchant information (authentication / transaction id)
                        ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = new merchantAuthenticationType()
                        {
                            name            = apiLogin,
                            ItemElementName = ItemChoiceType.transactionKey,
                            Item            = transactionKey,
                        };
                        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 Results
                                foreach (var item in item1)
                                {
                                    writer.WriteRow(item);
                                }
                            }
                            var request = new createTransactionRequest {
                                transactionRequest = transactionRequest
                            };

                            // instantiate the contoller that will call the service
                            var controller = new createTransactionController(request);
                            controller.Execute();

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

                            //validate
                            if (response != null)
                            {
                                if (response.messages.resultCode == messageTypeEnum.Ok)
                                {
                                    if (response.transactionResponse.messages != null)
                                    {
                                        /*****************************/
                                        try
                                        {
                                            //Assert.AreEqual(response.Id, customerProfileId);
                                            CsvRow row1 = new CsvRow();
                                            row1.Add("CTCC_00" + flag.ToString());
                                            row1.Add("ChargeTokenizedCreditCard");
                                            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("Successfully created transaction with Transaction ID: " + response.transactionResponse.transId);
                                            Console.WriteLine("Response Code: " + response.transactionResponse.responseCode);
                                            Console.WriteLine("Message Code: " + response.transactionResponse.messages[0].code);
                                            Console.WriteLine("Description: " + response.transactionResponse.messages[0].description);
                                            Console.WriteLine("Success, Auth Code : " + response.transactionResponse.authCode);
                                        }
                                        catch
                                        {
                                            CsvRow row1 = new CsvRow();
                                            row1.Add("CTCC_00" + flag.ToString());
                                            row1.Add("ChargeTokenizedCreditCard");
                                            row1.Add("Assertion Failed!");
                                            row1.Add(DateTime.Now.ToString("yyyy/MM/dd" + "::" + "HH:mm:ss:fff"));
                                            writer.WriteRow(row1);
                                            flag = flag + 1;
                                        }
                                        /*******************/
                                    }
                                    else
                                    {
                                        Console.WriteLine("Failed Transaction.");
                                        if (response.transactionResponse.errors != null)
                                        {
                                            Console.WriteLine("Error Code: " + response.transactionResponse.errors[0].errorCode);
                                            Console.WriteLine("Error message: " + response.transactionResponse.errors[0].errorText);
                                        }
                                    }
                                }
                                else
                                {
                                    Console.WriteLine("Failed Transaction.");
                                    CsvRow row2 = new CsvRow();
                                    row2.Add("CTCC_00" + flag.ToString());
                                    row2.Add("ChargeTokenizedCreditCard");
                                    row2.Add("Fail");
                                    row2.Add(DateTime.Now.ToString("yyyy/MM/dd" + "::" + "HH:mm:ss:fff"));
                                    writer.WriteRow(row2);
                                    flag = flag + 1;
                                    //if (response.transactionResponse != null && response.transactionResponse.errors != null)
                                    //{
                                    //    Console.WriteLine("Error Code: " + response.transactionResponse.errors[0].errorCode);
                                    //    Console.WriteLine("Error message: " + response.transactionResponse.errors[0].errorText);
                                    //}
                                    //else
                                    //{
                                    //    Console.WriteLine("Error Code: " + response.messages.message[0].code);
                                    //    Console.WriteLine("Error message: " + response.messages.message[0].text);
                                    //}
                                }
                            }
                            else
                            {
                                Console.WriteLine("Null Response.");
                                CsvRow row2 = new CsvRow();
                                row2.Add("CTCC_00" + flag.ToString());
                                row2.Add("ChargeTokenizedCreditCard");
                                row2.Add("Fail");
                                row2.Add(DateTime.Now.ToString("yyyy/MM/dd" + "::" + "HH:mm:ss:fff"));
                                writer.WriteRow(row2);
                                flag = flag + 1;
                            }
                        }



                        //return response;
                        catch (Exception e)
                        {
                            CsvRow row2 = new CsvRow();
                            row2.Add("CTCC_00" + flag.ToString());
                            row2.Add("ChargeTokenizedCreditCard");
                            row2.Add("Fail");
                            row2.Add(DateTime.Now.ToString("yyyy/MM/dd" + "::" + "HH:mm:ss:fff"));
                            writer.WriteRow(row2);
                            flag = flag + 1;
                            Console.WriteLine(TestCaseId + " Error Message " + e.Message);
                        }
                    }
                }
            }
        }
Example #22
0
        public static ANetApiResponse Run(string ApiLoginID, string ApiTransactionKey, string subscriptionId)
        {
            Console.WriteLine("Update Subscription Sample");

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

            paymentScheduleType schedule = new paymentScheduleType
            {
                startDate        = DateTime.Now.AddDays(1), // start date should be tomorrow
                totalOccurrences = 9999                     // 999 indicates no end date
            };

            #region Payment Information
            var creditCard = new creditCardType
            {
                cardNumber     = "4111111111111111",
                expirationDate = "1028"
            };

            //standard api call to retrieve response
            paymentType cc = new paymentType {
                Item = creditCard
            };
            #endregion

            nameAndAddressType addressInfo = new nameAndAddressType()
            {
                firstName = "Calvin",
                lastName  = "Brown"
            };

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

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

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

            ARBUpdateSubscriptionResponse response = controller.GetApiResponse();

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

            return(response);
        }
        public static ResponseHandler Run(decimal amount)
        {
            Console.WriteLine("Charge Credit Card Sample");

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

            // define the merchant information (authentication / transaction id)
            ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = new merchantAuthenticationType()
            {
                name            = "9ZtJvb59pK",
                ItemElementName = ItemChoiceType.transactionKey,
                Item            = "73A9F4v7NEnj76BJ",
            };

            var creditCard = new creditCardType
            {
                cardNumber     = "4111111111111111",
                expirationDate = "1028",
                cardCode       = "123"
            };

            var billingAddress = new customerAddressType
            {
                firstName = "John",
                lastName  = "Doe",
                address   = "123 My St",
                city      = "OurTown",
                zip       = "98004"
            };

            //standard api call to retrieve response
            var paymentType = new paymentType {
                Item = creditCard
            };

            // Add line Items
            var lineItems = new lineItemType[2];

            lineItems[0] = new lineItemType {
                itemId = "1", name = "t-shirt", quantity = 2, unitPrice = new Decimal(15.00)
            };
            lineItems[1] = new lineItemType {
                itemId = "2", name = "snowboard", quantity = 1, unitPrice = new Decimal(450.00)
            };

            var transactionRequest = new transactionRequestType
            {
                transactionType = transactionTypeEnum.authCaptureTransaction.ToString(),    // charge the card

                amount    = amount,
                payment   = paymentType,
                billTo    = billingAddress,
                lineItems = lineItems,
            };

            var request = new createTransactionRequest {
                transactionRequest = transactionRequest
            };

            // instantiate the controller that will call the service
            var controller = new createTransactionController(request);

            controller.Execute();

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

            // validate response
            if (response != null)
            {
                if (response.messages.resultCode == messageTypeEnum.Ok)
                {
                    if (response.transactionResponse.messages != null)
                    {
                        ResponseHandler handler = new ResponseHandler();
                        handler.check    = true;
                        handler.response = response.transactionResponse.transId;
                        return(handler);
                    }
                    else
                    {
                        if (response.transactionResponse.errors != null)
                        {
                            ResponseHandler handler = new ResponseHandler();
                            handler.check    = false;
                            handler.response = response.transactionResponse.errors[0].errorText;
                            return(handler);
                        }
                        return(null);
                    }
                }
                else
                {
                    if (response.transactionResponse != null && response.transactionResponse.errors != null)
                    {
                        ResponseHandler handler = new ResponseHandler();
                        handler.check    = false;
                        handler.response = response.transactionResponse.errors[0].errorText;
                        return(handler);
                    }
                    else
                    {
                        ResponseHandler handler = new ResponseHandler();
                        handler.check    = false;
                        handler.response = response.messages.message[0].text;
                        return(handler);
                    }
                }
            }
            else
            {
                return(null);
            }
        }
        /// <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. hece 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 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 = $"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);
        }
Example #25
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;
        }
        public static ANetApiResponse Run(String ApiLoginID, String ApiTransactionKey, decimal amount)
        {
            Console.WriteLine("Authorize Credit Card Sample");

            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,
            };

            var creditCard = new creditCardType
            {
                cardNumber     = "4111111111111111",
                expirationDate = "0725"
            };

            //standard api call to retrieve response
            var paymentType = new paymentType {
                Item = creditCard
            };

            var transactionRequest = new transactionRequestType
            {
                transactionType = transactionTypeEnum.authOnlyTransaction.ToString(),    // authorize only
                amount          = amount,
                payment         = paymentType
            };

            var request = new createTransactionRequest {
                transactionRequest = transactionRequest
            };

            // instantiate the controller that will call the service
            var controller = new createTransactionController(request);

            controller.Execute();

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

            // validate response
            if (response != null)
            {
                if (response.messages.resultCode == messageTypeEnum.Ok)
                {
                    if (response.transactionResponse.messages != null)
                    {
                        Console.WriteLine("Successfully created transaction with Transaction ID: " + response.transactionResponse.transId);
                        Console.WriteLine("Response Code: " + response.transactionResponse.responseCode);
                        Console.WriteLine("Message Code: " + response.transactionResponse.messages[0].code);
                        Console.WriteLine("Description: " + response.transactionResponse.messages[0].description);
                        Console.WriteLine("Success, Auth Code : " + response.transactionResponse.authCode);
                    }
                    else
                    {
                        Console.WriteLine("Failed Transaction.");
                        if (response.transactionResponse.errors != null)
                        {
                            Console.WriteLine("Error Code: " + response.transactionResponse.errors[0].errorCode);
                            Console.WriteLine("Error message: " + response.transactionResponse.errors[0].errorText);
                        }
                    }
                }
                else
                {
                    Console.WriteLine("Failed Transaction.");
                    if (response.transactionResponse != null && response.transactionResponse.errors != null)
                    {
                        Console.WriteLine("Error Code: " + response.transactionResponse.errors[0].errorCode);
                        Console.WriteLine("Error message: " + response.transactionResponse.errors[0].errorText);
                    }
                    else
                    {
                        Console.WriteLine("Error Code: " + response.messages.message[0].code);
                        Console.WriteLine("Error message: " + response.messages.message[0].text);
                    }
                }
            }
            else
            {
                Console.WriteLine("Null Response.");
            }

            return(response);
        }
        public static void Run(String ApiLoginID, String ApiTransactionKey)
        {
            Console.WriteLine("Running CaptureFundsAuthorizedThroughAnotherChannel Sample ...");

            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,
            };

            var creditCard = new creditCardType
            {
                // Change the cardNumber and expiration Date as required
                cardNumber     = "4111111111111111",
                expirationDate = "0718"
            };

            //standard api call to retrieve response
            var paymentType = new paymentType {
                Item = creditCard
            };

            var transactionRequest = new transactionRequestType
            {
                // capture the funds that authorized through another channel
                transactionType = transactionTypeEnum.captureOnlyTransaction.ToString(),
                // Change the amount that needs to be captured as required
                amount  = 133.45m,
                payment = paymentType,
                // Change the authCode that came from successfully authorized transaction through any channel.
                authCode = "ROHNFQ"
            };

            var request = new createTransactionRequest
            {
                transactionRequest = transactionRequest
            };

            // instantiate the contoller that will call the service
            var controller = new createTransactionController(request);

            controller.Execute();

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

            if (response.messages.resultCode == messageTypeEnum.Ok)
            {
                if (response.transactionResponse != null)
                {
                    Console.WriteLine("Success, Auth Code : " + response.transactionResponse.authCode);
                }
            }
            else
            {
                Console.WriteLine("Error: " + response.messages.message[0].code + "  " + response.messages.message[0].text);
                if (response.transactionResponse != null)
                {
                    Console.WriteLine("Transaction Error : " + response.transactionResponse.errors[0].errorCode + " " + response.transactionResponse.errors[0].errorText);
                }
            }
        }