Exemple #1
0
        /// <summary>
        /// Submits the transaction.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        private ReplyMessage SubmitTransaction(FinancialGateway financialGateway, RequestMessage request)
        {
            ReplyMessage reply          = new ReplyMessage();
            string       merchantID     = GetAttributeValue(financialGateway, "MerchantID");
            string       transactionkey = GetAttributeValue(financialGateway, "TransactionKey");

            BasicHttpBinding binding = new BasicHttpBinding();

            binding.Name                                = "ITransactionProcessor";
            binding.MaxBufferSize                       = 2147483647;
            binding.MaxBufferPoolSize                   = 2147483647;
            binding.MaxReceivedMessageSize              = 2147483647;
            binding.ReaderQuotas.MaxDepth               = 2147483647;
            binding.ReaderQuotas.MaxArrayLength         = 2147483647;
            binding.ReaderQuotas.MaxBytesPerRead        = 2147483647;
            binding.ReaderQuotas.MaxStringContentLength = 2147483647;
            binding.Security.Mode                       = BasicHttpSecurityMode.TransportWithMessageCredential;
            EndpointAddress address = new EndpointAddress(new Uri(GetGatewayUrl(financialGateway)));

            var proxy = new TransactionProcessorClient(binding, address);

            proxy.ClientCredentials.UserName.UserName = merchantID;
            proxy.ClientCredentials.UserName.Password = transactionkey;
            proxy.Endpoint.Address = address;
            proxy.Endpoint.Binding = binding;

            try
            {
                reply = proxy.runTransaction(request);
                return(reply);
            }
            catch (TimeoutException e)
            {
                reply.reasonCode     = "151";
                reply.additionalData = e.ToString();
                return(reply);
            }
            catch (FaultException e)
            {
                reply.reasonCode     = "150";
                reply.additionalData = e.ToString();
                return(reply);
            }
            catch (Exception e)
            {
                reply.reasonCode     = "";
                reply.additionalData = e.ToString();
                return(reply);
            }
        }
        /// <summary>
        /// Sends a CyberSource transaction request.
        /// </summary>
        /// <param name="config">Configuration object to use.</param>
        /// <param name="requestMessage">RequestMessage object containing the request.</param>
        /// <returns>ReplyMessage containing the reply.</returns>
        public static ReplyMessage RunTransaction(
            Configuration config, RequestMessage requestMessage)
        {
            Logger logger = null;
            TransactionProcessorClient proc = null;

            try
            {
                DetermineEffectiveMerchantID(ref config, requestMessage);
                SetVersionInformation(requestMessage);
                logger = PrepareLog(config);
                SetConnectionLimit(config);


                CustomBinding currentBinding = getWCFCustomBinding(config);


                //Setup endpoint Address with dns identity
                AddressHeaderCollection headers         = new AddressHeaderCollection();
                EndpointAddress         endpointAddress = new EndpointAddress(new Uri(config.EffectiveServerURL), EndpointIdentity.CreateDnsIdentity(config.EffectivePassword), headers);

                //Get instance of service
                using (proc = new TransactionProcessorClient(currentBinding, endpointAddress))
                {
                    // set the timeout
                    TimeSpan timeOut = new TimeSpan(0, 0, 0, config.Timeout, 0);
                    currentBinding.SendTimeout = timeOut;

                    //add certificate credentials
                    string keyFilePath = Path.Combine(config.KeysDirectory, config.EffectiveKeyFilename);

                    X509Certificate2 merchantCert = null;
                    X509Certificate2 cybsCert     = null;
                    DateTime         dateFile     = File.GetLastWriteTime(keyFilePath);
                    if (config.CertificateCacheEnabled)
                    {
                        if (!merchantIdentities.ContainsKey(config.MerchantID) || IsMerchantCertExpired(logger, config.MerchantID, dateFile, merchantIdentities))
                        {
                            if (logger != null)
                            {
                                logger.LogInfo("Loading certificate for merchantID " + config.MerchantID);
                            }

                            X509Certificate2Collection collection = new X509Certificate2Collection();
                            collection.Import(keyFilePath, config.EffectivePassword, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);

                            X509Certificate2 newMerchantCert = null;
                            X509Certificate2 newCybsCert     = null;

                            foreach (X509Certificate2 cert1 in collection)
                            {
                                if (cert1.Subject.Contains(config.MerchantID))
                                {
                                    newMerchantCert = cert1;
                                }

                                if (cert1.Subject.Contains(CYBS_SUBJECT_NAME))
                                {
                                    newCybsCert = cert1;
                                }
                            }
                            CertificateEntry newCert = new CertificateEntry
                            {
                                ModifiedTime = dateFile,
                                CybsCert     = newCybsCert,
                                MerchantCert = newMerchantCert
                            };
                            merchantIdentities.AddOrUpdate(config.MerchantID, newCert, (x, y) => newCert);
                        }
                        merchantCert = GetOrFindValidMerchantCertFromStore(config.MerchantID, merchantIdentities);
                        if (config.UseSignedAndEncrypted)
                        {
                            cybsCert = GetOrFindValidCybsCertFromStore(config.MerchantID, merchantIdentities);
                        }
                    }
                    else
                    {
                        // Changes for SHA2 certificates support
                        X509Certificate2Collection collection = new X509Certificate2Collection();
                        collection.Import(keyFilePath, config.EffectivePassword, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);

                        foreach (X509Certificate2 cert1 in collection)
                        {
                            if (cert1.Subject.Contains(config.MerchantID))
                            {
                                merchantCert = cert1;
                                break;
                            }
                        }

                        if (config.UseSignedAndEncrypted)
                        {
                            foreach (X509Certificate2 cert2 in collection)
                            {
                                //Console.WriteLine(cert1.Subject);
                                if (cert2.Subject.Contains(CYBERSOURCE_PUBLIC_KEY))
                                {
                                    cybsCert = cert2;
                                    break;
                                }
                            }
                        }
                    }

                    if (merchantCert == null)
                    {
                        throw new ApplicationException(
                                  "CONFIGURATION OR CODE BUG:  merchant certificate is missing, check the p12 file");
                    }
                    //Set protection level to sign only
                    proc.Endpoint.Contract.ProtectionLevel = System.Net.Security.ProtectionLevel.Sign;
                    proc.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;
                    proc.ClientCredentials.ClientCertificate.Certificate         = merchantCert;
                    proc.ClientCredentials.ServiceCertificate.DefaultCertificate = merchantCert;

                    if (config.UseSignedAndEncrypted)
                    {
                        if (cybsCert == null)
                        {
                            throw new ApplicationException(
                                      "CONFIGURATION OR CODE BUG:  cybs certificate is missing, check the p12 file");
                        }

                        //Set protection level to sign & encrypt only
                        proc.Endpoint.Contract.ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign;
                        proc.ClientCredentials.ServiceCertificate.DefaultCertificate = cybsCert;
                    }
                    // Changes for NGT-3035
                    XmlNode req = SerializeObjectToXmlNode(requestMessage);
                    if (logger != null)
                    {
                        logger.LogRequest(req, config.Demo);
                    }

                    ReplyMessage reply = proc.runTransaction(requestMessage);
                    XmlNode      rep   = SerializeObjectToXmlNode(reply);
                    if (logger != null)
                    {
                        logger.LogReply(rep, config.Demo);
                    }

                    return(reply);
                }
            }
            catch (Exception e)
            {
                if (logger != null)
                {
                    logger.LogException(e);
                }
                if (proc != null)
                {
                    proc.Abort();
                }
                throw;
            }
            finally
            {
                if (proc != null)
                {
                    proc.Close();
                }
            }
        }
Exemple #3
0
        /// <summary>
        /// Sends a CyberSource transaction request.
        /// </summary>
        /// <param name="config">Configuration object to use.</param>
        /// <param name="requestMessage">RequestMessage object containing the request.</param>
        /// <returns>ReplyMessage containing the reply.</returns>
        public static ReplyMessage RunTransaction(
            Configuration config, RequestMessage requestMessage)
        {
            Logger logger = null;
            TransactionProcessorClient proc = null;

            try
            {
                DetermineEffectiveMerchantID(ref config, requestMessage);
                SetVersionInformation(requestMessage);
                logger = PrepareLog(config);
                SetConnectionLimit(config);


                CustomBinding currentBinding = getWCFCustomBinding(config);


                //Setup endpoint Address with dns identity
                AddressHeaderCollection headers         = new AddressHeaderCollection();
                EndpointAddress         endpointAddress = new EndpointAddress(new Uri(config.EffectiveServerURL), EndpointIdentity.CreateDnsIdentity(config.EffectivePassword), headers);

                //Get instance of service
                using (proc = new TransactionProcessorClient(currentBinding, endpointAddress)){
                    //Set protection level to sign & encrypt only
                    proc.Endpoint.Contract.ProtectionLevel = System.Net.Security.ProtectionLevel.Sign;

                    // set the timeout
                    TimeSpan timeOut = new TimeSpan(0, 0, 0, config.Timeout, 0);
                    currentBinding.SendTimeout = timeOut;

                    //add certificate credentials
                    string keyFilePath = Path.Combine(config.KeysDirectory, config.EffectiveKeyFilename);
                    proc.ClientCredentials.ClientCertificate.Certificate = new X509Certificate2(keyFilePath, config.EffectivePassword, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);

                    proc.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;

                    // Changes for SHA2 certificates support
                    X509Certificate2Collection collection = new X509Certificate2Collection();
                    collection.Import(keyFilePath, config.EffectivePassword, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);

                    foreach (X509Certificate2 cert1 in collection)
                    {
                        if (cert1.Subject.Contains(config.MerchantID))
                        {
                            proc.ClientCredentials.ClientCertificate.Certificate         = cert1;
                            proc.ClientCredentials.ServiceCertificate.DefaultCertificate = cert1;
                            break;
                        }
                    }

                    if (config.UseSignedAndEncrypted)
                    {
                        foreach (X509Certificate2 cert2 in collection)
                        {
                            //Console.WriteLine(cert1.Subject);
                            if (cert2.Subject.Contains(CYBERSOURCE_PUBLIC_KEY))
                            {
                                //Set protection level to sign & encrypt only
                                proc.Endpoint.Contract.ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign;
                                proc.ClientCredentials.ServiceCertificate.DefaultCertificate = cert2;
                                break;
                            }
                        }
                    }

                    // send request now
                    // Changes for NGT-3035
                    XmlNode req = SerializeObjectToXmlNode(requestMessage);
                    if (logger != null)
                    {
                        logger.LogRequest(req, config.Demo);
                    }

                    ReplyMessage reply = proc.runTransaction(requestMessage);
                    XmlNode      rep   = SerializeObjectToXmlNode(reply);
                    if (logger != null)
                    {
                        logger.LogReply(rep, config.Demo);
                    }

                    return(reply);
                }
            }
            catch (Exception e)
            {
                if (logger != null)
                {
                    logger.LogException(e);
                }
                if (proc != null)
                {
                    proc.Abort();
                }
                throw;
            }
            finally
            {
                if (proc != null)
                {
                    proc.Close();
                }
            }
        }
Exemple #4
0
        public ActionResult CreateBilling(UserBillingInformationInput input)
        {
            if (!ModelState.IsValid)
            {
                ViewBag.errMessages = string.Join("; ", ModelState.Values
                                                  .SelectMany(x => x.Errors)
                                                  .Select(x => x.ErrorMessage));

                return(View(input));
            }

            // var xPrice = (decimal)input.SpecialPostingCost;
            if (!ModelState.IsValid)
            {
                return(View(input));
            }

            //be sure the amount paid is the amount required*/

            RequestMessage request = new RequestMessage();

            request.merchantID = MERCHANT_ID;

            // To help us troubleshoot any problems that you may encounter,
            // please include the following information about your application.
            request.clientLibrary        = ".NET WCF";
            request.clientLibraryVersion = Environment.Version.ToString();
            request.clientEnvironment    =
                Environment.OSVersion.Platform +
                Environment.OSVersion.Version.ToString();

            // This section contains a sample transaction request for the authorization
            // service with complete billing, payment card, and purchase (two items) information.
            request.ccAuthService     = new CCAuthService();
            request.ccAuthService.run = "true";


            BillTo billTo = new BillTo();

            billTo.firstName   = input.FirstName;
            billTo.lastName    = input.LastName;
            billTo.street1     = input.BillingAddress;
            billTo.city        = input.City;
            billTo.postalCode  = input.BillingZipCode;
            billTo.country     = input.Country;
            billTo.email       = input.BillingContactEmail;
            billTo.ipAddress   = GetPublicIP();
            billTo.phoneNumber = input.BillingContactNumber;

            request.billTo = billTo;

            Card card = new Card();

            card.accountNumber   = input.CreditCardNumber; // "4111111111111111";
            card.expirationMonth = input.ExpiryDate.PadLeft(2);
            card.expirationYear  = input.ExpiryDate.PadRight(4);
            card.cvNumber        = input.CardCode;
            request.card         = card;

            PurchaseTotals purchaseTotals = new PurchaseTotals();

            purchaseTotals.currency = "SGD";
            if (input.Subscription.Equals("100$/Month"))
            {
                purchaseTotals.originalAmount = "100";
            }
            else if (input.Subscription.Equals("600$/Semi-Annual"))
            {
                purchaseTotals.originalAmount = "600";
            }
            else if (input.Subscription.Equals("1200$/Annual"))
            {
                purchaseTotals.originalAmount = "1200";
            }
            request.purchaseTotals = purchaseTotals;

            // Before using this example, replace the generic value with your
            // reference number for the current transaction.
            request.merchantReferenceCode = "U" + input.UserId + "A" + purchaseTotals.originalAmount;
            request.item = new Item[1];

            Item item = new Item();

            item.id         = "0";
            item.unitPrice  = purchaseTotals.originalAmount;
            request.item[0] = item;


            try
            {
                TransactionProcessorClient proc = new TransactionProcessorClient();

                proc.ChannelFactory.Credentials.UserName.UserName = request.merchantID;
                proc.ChannelFactory.Credentials.UserName.Password = TRANSACTION_KEY;

                ReplyMessage reply = proc.runTransaction(request);

                if (reply.decision == "ACCEPT")
                {
                    SaveOrderState();
                    ProcessReply(reply);
                    var userBillingInformation = service.Create(new UserBillingInformation
                    {
                        FirstName            = input.FirstName,
                        LastName             = input.LastName,
                        BillingAddress       = input.BillingAddress,
                        BillingZipCode       = input.BillingZipCode,
                        BillingContactNumber = input.BillingContactNumber,
                        BillingContactEmail  = input.BillingContactEmail,
                        CreditCardNumber     = input.CreditCardNumber,
                        ExpiryDate           = input.ExpiryDate,
                        UserId = input.UserId
                    });

                    service.Save();

                    var user = serviceUser.Where(o => o.Id.Equals(input.UserId)).SingleOrDefault();

                    User selectedUser = serviceUser.Get(user.Id);
                    selectedUser.PaymentStatus = "Active";
                    serviceUser.Save();


                    using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Db"].ConnectionString))
                        using (var command = new SqlCommand("sp_send_dbmail", conn)
                        {
                            CommandType = CommandType.StoredProcedure
                        })
                        {
                            conn.Open();
                            command.Parameters.Add(new SqlParameter("@profile_name", "DBMail Profile"));
                            command.Parameters.Add(new SqlParameter("@recipients", input.BillingContactEmail));
                            command.Parameters.Add(new SqlParameter("@subject", "AppWiz Billing Info registration"));
                            command.Parameters.Add(new SqlParameter("@from_address",
                                                                    ConfigurationManager.AppSettings["EmailHost"]));
                            command.Parameters.Add(new SqlParameter("@Body", "AppWiz payment acknowledgement."));
                            command.ExecuteNonQuery();
                            conn.Close();
                        }
                    return(RedirectToAction("Index", "Application"));
                }
            }
            catch (TimeoutException e)
            {
                //Console.WriteLine("TimeoutException: " + e.Message + "\n" + e.StackTrace);
                // return Json("TimeoutException: " + e.Message + "\n" + e.StackTrace);
                return(Json(false));
            }
            catch (FaultException e)
            {
                //Console.WriteLine("FaultException: " + e.Message + "\n" + e.StackTrace);
                return(Json(false));
            }
            catch (CommunicationException e)
            {
                //Console.WriteLine("CommunicationException: " + e.Message + "\n" + e.StackTrace);
                return(Json(false));
            }

            return(Json(false));
        }
        public ActionResult SetPayment(int consumerId, string firstName, string lastName, string billingAddress,
                                       string billingZipCode, long creditCardNumber, string creditCardSecurityCode,
                                       string expiryDate, decimal amount, long phone, string email, string ipAddress, string city, string country)
        {
            if (firstName.Length > 0 && lastName.Length > 0 && billingAddress.Length > 0 && billingZipCode.Length > 0 &&
                creditCardNumber > 0 && creditCardSecurityCode.Length > 0 && ipAddress.Length > 0 && city.Length > 0)
            {
                //Authorize.net start
                // var gate = OpenGateway();

                // //build the request from the Form post
                //var apiRequest = CheckoutFormReaders.BuildAuthAndCaptureFromPost();

                //apiRequest.Amount = amount.ToString();

                //apiRequest.DelimData = "tRUE";
                //apiRequest.DelimChar = "|";
                //apiRequest.RelayResponse = "FALSE";
                //apiRequest.Type = "AUTH_CAPTURE";
                //apiRequest.Method = "CC";
                //apiRequest.CardNum = creditCardNumber.ToString();
                //apiRequest.ExpDate = expiryDate;

                //apiRequest.Description = "Payment for purchase from ....";
                //apiRequest.FirstName = firstName;
                //apiRequest.LastName = lastName;
                //apiRequest.Address = billingAddress;
                //apiRequest.Phone = phone.ToString();
                //apiRequest.Email = email;
                //apiRequest.Zip = billingZipCode;
                //apiRequest.CardCode = creditCardSecurityCode;

                ////send to Auth.NET
                //var response = gate.Send(apiRequest);

                ////be sure the amount paid is the amount required

                //if (response.Approved)
                //Authorize.net end

                RequestMessage request = new RequestMessage();

                request.merchantID = MERCHANT_ID;



                // To help us troubleshoot any problems that you may encounter,
                // please include the following information about your application.
                request.clientLibrary        = ".NET WCF";
                request.clientLibraryVersion = Environment.Version.ToString();
                request.clientEnvironment    =
                    Environment.OSVersion.Platform +
                    Environment.OSVersion.Version.ToString();

                // This section contains a sample transaction request for the authorization
                // service with complete billing, payment card, and purchase (two items) information.
                request.ccAuthService     = new CCAuthService();
                request.ccAuthService.run = "true";

                BillTo billTo = new BillTo();
                billTo.firstName   = firstName;
                billTo.lastName    = lastName;
                billTo.street1     = billingAddress;
                billTo.city        = city;
                billTo.postalCode  = billingZipCode;
                billTo.country     = country;
                billTo.email       = email;
                billTo.ipAddress   = ipAddress;
                billTo.phoneNumber = phone.ToString();
                request.billTo     = billTo;

                Card card = new Card();
                card.accountNumber   = creditCardNumber.ToString(); // "4111111111111111";
                card.expirationMonth = expiryDate.Substring(0, 2);
                card.expirationYear  = expiryDate.Substring(3, 4);

                card.cvNumber = creditCardSecurityCode;
                request.card  = card;

                PurchaseTotals purchaseTotals = new PurchaseTotals();
                purchaseTotals.currency       = "SGD";
                purchaseTotals.originalAmount = amount.ToString();
                request.purchaseTotals        = purchaseTotals;

                var totals = serviceTransaction.Where(o => o.ConsumerId == consumerId && o.Status == "Pending").FirstOrDefault();
                var orders = repoOrder.Where(x => x.ConsumerId == consumerId && x.TransactionId == totals.Id);

                // Before using this example, replace the generic value with your
                // reference number for the current transaction.
                request.merchantReferenceCode = "T" + totals.Id.ToString() + "C" + totals.ConsumerId.ToString() + "D" + totals.DateofTransaction.ToString();
                request.item = new Item[orders.Count()];

                int ctr = 0;
                foreach (var order in orders)
                {
                    Item item = new Item();
                    item.id           = ctr.ToString();
                    item.unitPrice    = order.Total.ToString();
                    request.item[ctr] = item;
                    ctr++;
                }

                try
                {
                    TransactionProcessorClient proc = new TransactionProcessorClient();

                    proc.ChannelFactory.Credentials.UserName.UserName = request.merchantID;
                    proc.ChannelFactory.Credentials.UserName.Password = TRANSACTION_KEY;

                    ReplyMessage reply = proc.runTransaction(request);

                    if (reply.decision == "ACCEPT")
                    {
                        SaveOrderState();
                        ProcessReply(reply);
                        var billingInfo = service.Where(o => o.ConsumerId == consumerId).FirstOrDefault();

                        if (billingInfo == null)
                        {
                            var consumerBillingInformation = service.Create(new mm.ConsumerBillingInformation
                            {
                                FirstName            = firstName,
                                LastName             = lastName,
                                BillingAddress       = billingAddress,
                                BillingZipCode       = billingZipCode,
                                BillingContactNumber = phone.ToString(),
                                BillingContactEmail  = email,
                                CreditCardNumber     = creditCardNumber.ToString(),
                                ExpiryDate           = expiryDate,
                                ConsumerId           = consumerId
                            });

                            service.Save();
                        }


                        mm.Transaction selectedTransaction = serviceTransaction.Get(totals.Id);
                        selectedTransaction.Status = "Paid";
                        serviceTransaction.Save();

                        using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Db"].ConnectionString))
                            using (var command = new SqlCommand("sp_send_dbmail", conn)
                            {
                                CommandType = CommandType.StoredProcedure
                            })
                            {
                                conn.Open();
                                command.Parameters.Add(new SqlParameter("@profile_name", "DBMail Profile"));
                                command.Parameters.Add(new SqlParameter("@recipients", email));
                                command.Parameters.Add(new SqlParameter("@subject", "Some application purchase"));
                                command.Parameters.Add(new SqlParameter("@from_address", ConfigurationManager.AppSettings["EmailHost"]));
                                command.Parameters.Add(new SqlParameter("@Body", "temporary message."));
                                command.ExecuteNonQuery();
                                conn.Close();
                            }
                        return(Json(true));
                    }
                    else
                    {
                        return(Json(false));
                    }

                    //// To retrieve individual reply fields, follow these examples.
                    //Console.WriteLine("decision = " + reply.decision);
                    //Console.WriteLine("reasonCode = " + reply.reasonCode);
                    //Console.WriteLine("requestID = " + reply.requestID);
                    //Console.WriteLine("requestToken = " + reply.requestToken);
                    //Console.WriteLine("ccAuthReply.reasonCode = " + reply.ccAuthReply.reasonCode);
                }
                catch (TimeoutException e)
                {
                    //Console.WriteLine("TimeoutException: " + e.Message + "\n" + e.StackTrace);
                    // return Json("TimeoutException: " + e.Message + "\n" + e.StackTrace);
                    return(Json(false));
                }
                catch (FaultException e)
                {
                    //Console.WriteLine("FaultException: " + e.Message + "\n" + e.StackTrace);
                    return(Json(false));
                }
                catch (CommunicationException e)
                {
                    //Console.WriteLine("CommunicationException: " + e.Message + "\n" + e.StackTrace);
                    return(Json(false));
                }
            }
            return(Json(false));
        }
    static void Main(string[] args)
    {
        RequestMessage request = new RequestMessage();

        request.merchantID = MERCHANT_ID;

        // Before using this example, replace the generic value with your
        // reference number for the current transaction.
        request.merchantReferenceCode = "test01";

        // To help us troubleshoot any problems that you may encounter,
        // please include the following information about your application.
        request.clientLibrary = ".NET WCF";
        request.clientLibraryVersion = Environment.Version.ToString();
        request.clientEnvironment =
            Environment.OSVersion.Platform +
            Environment.OSVersion.Version.ToString();

        // This section contains a sample transaction request for the authorization
        // service with complete billing, payment card, and purchase (two items) information.
        request.ccAuthService = new CCAuthService();
        request.ccAuthService.run = "true";

        BillTo billTo = new BillTo();
        billTo.firstName = "John";
        billTo.lastName = "Doe";
        billTo.street1 = "1295 Charleston Road";
        billTo.city = "Mountain View";
        billTo.state = "CA";
        billTo.postalCode = "94043";
        billTo.country = "US";
        billTo.email = "*****@*****.**";
        billTo.ipAddress = "10.7.111.111";
        request.billTo = billTo;

        Card card = new Card();
        card.accountNumber = "4111111111111111";
        card.expirationMonth = "12";
        card.expirationYear = "2020";
        request.card = card;

        PurchaseTotals purchaseTotals = new PurchaseTotals();
        purchaseTotals.currency = "USD";
        request.purchaseTotals = purchaseTotals;

        request.item = new Item[2];

        Item item = new Item();
        item.id = "0";
        item.unitPrice = "12.34";
        request.item[0] = item;

        item = new Item();
        item.id = "1";
        item.unitPrice = "56.78";
        request.item[1] = item;

        try
        {
            TransactionProcessorClient proc = new TransactionProcessorClient();

            proc.ChannelFactory.Credentials.UserName.UserName = request.merchantID;
            proc.ChannelFactory.Credentials.UserName.Password = TRANSACTION_KEY;

            ReplyMessage reply = proc.runTransaction(request);

            // To retrieve individual reply fields, follow these examples.
            Console.WriteLine("decision = " + reply.decision);
            Console.WriteLine("reasonCode = " + reply.reasonCode);
            Console.WriteLine("requestID = " + reply.requestID);
            Console.WriteLine("requestToken = " + reply.requestToken);
            Console.WriteLine("ccAuthReply.reasonCode = " + reply.ccAuthReply.reasonCode);
        }
        catch (TimeoutException e)
        {
            Console.WriteLine("TimeoutException: " + e.Message + "\n" + e.StackTrace);
        }
        catch (FaultException e)
        {
            Console.WriteLine("FaultException: " + e.Message + "\n" + e.StackTrace);
        }
        catch (CommunicationException e)
        {
            Console.WriteLine("CommunicationException: " + e.Message + "\n" + e.StackTrace);
        }
    }
        /// <summary>
        /// Sends a CyberSource transaction request.
        /// </summary>
        /// <param name="config">Configuration object to use.</param>
		/// <param name="requestMessage">RequestMessage object containing the request.</param>
		/// <returns>ReplyMessage containing the reply.</returns>
        public static ReplyMessage RunTransaction(
            Configuration config, RequestMessage requestMessage)
        {

            Logger logger = null;
            TransactionProcessorClient proc = null;
			try
			{

                DetermineEffectiveMerchantID(ref config, requestMessage);
                SetVersionInformation(requestMessage);
                logger = PrepareLog(config);
                SetConnectionLimit(config);


                CustomBinding currentBinding = getWCFCustomBinding();


                //Setup endpoint Address with dns identity
                AddressHeaderCollection headers = new AddressHeaderCollection();
                EndpointAddress endpointAddress = new EndpointAddress( new Uri(config.EffectiveServerURL), EndpointIdentity.CreateDnsIdentity(config.EffectivePassword), headers );
                
                //Get instance of service
                using( proc = new TransactionProcessorClient(currentBinding, endpointAddress)){
                
                    //Set protection level to sign only
                    proc.Endpoint.Contract.ProtectionLevel = System.Net.Security.ProtectionLevel.Sign;

                    // set the timeout
                    TimeSpan timeOut = new TimeSpan(0, 0, 0, config.Timeout, 0);
                    currentBinding.SendTimeout = timeOut;
              
                    //add certificate credentials
                    string keyFilePath = Path.Combine(config.KeysDirectory,config.EffectiveKeyFilename);
                    proc.ClientCredentials.ClientCertificate.Certificate = new X509Certificate2(keyFilePath,config.EffectivePassword, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);

                    proc.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;

                    // Changes for SHA2 certificates support
                    X509Certificate2Collection collection = new X509Certificate2Collection();
                    collection.Import(keyFilePath, config.EffectivePassword, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);

                    foreach (X509Certificate2 cert1 in collection)
                    {
                        if (cert1.Subject.Contains(config.MerchantID))
                        {
                            proc.ClientCredentials.ClientCertificate.Certificate = cert1;
                            proc.ClientCredentials.ServiceCertificate.DefaultCertificate = cert1;
                            break;
                        }
                    }

                    // send request now
                    // Changes for NGT-3035
                    XmlNode req = SerializeObjectToXmlNode(requestMessage);
                    if (logger != null)
                    {
                        logger.LogRequest(req, config.Demo);
                    }                   
                    
                    ReplyMessage reply = proc.runTransaction(requestMessage);
                    XmlNode rep = SerializeObjectToXmlNode(reply);
                    if (logger != null)
                    {
                        logger.LogReply(rep, config.Demo);
                    }  
                   
                    return (reply);
                }
			}
		    catch (Exception e)
            {
                if (logger != null)
                {
                    logger.LogException(e);
                }
                if (proc != null)
                {
                    proc.Abort();
                }
                throw;
            }
            finally
            {
                if (proc != null)
                {
                    proc.Close();
                }
            }
        }
Exemple #8
0
        /// <summary>
        /// Sends a CyberSource transaction request.
        /// </summary>
        /// <param name="config">Configuration object to use.</param>
        /// <param name="requestMessage">RequestMessage object containing the request.</param>
        /// <returns>ReplyMessage containing the reply.</returns>
        public static ReplyMessage RunTransaction(
            Configuration config, RequestMessage requestMessage)
        {
            Logger logger = null;
            TransactionProcessorClient proc = null;

            try
            {
                DetermineEffectiveMerchantID(ref config, requestMessage);
                SetVersionInformation(requestMessage);
                logger = PrepareLog(config);
                SetConnectionLimit(config);


                CustomBinding currentBinding = getWCFCustomBinding();


                //Setup endpoint Address with dns identity
                AddressHeaderCollection headers         = new AddressHeaderCollection();
                EndpointAddress         endpointAddress = new EndpointAddress(new Uri(config.EffectiveServerURL), EndpointIdentity.CreateDnsIdentity(config.EffectivePassword), headers);

                //Get instance of service
                using (proc = new TransactionProcessorClient(currentBinding, endpointAddress)){
                    //Set protection level to sign only
                    proc.Endpoint.Contract.ProtectionLevel = System.Net.Security.ProtectionLevel.Sign;

                    // set the timeout
                    TimeSpan timeOut = new TimeSpan(0, 0, 0, config.Timeout, 0);
                    currentBinding.SendTimeout = timeOut;

                    //add certificate credentials
                    string keyFilePath = Path.Combine(config.KeysDirectory, config.EffectiveKeyFilename);
                    proc.ClientCredentials.ClientCertificate.Certificate = new X509Certificate2(keyFilePath, config.EffectivePassword, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);

                    proc.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;
                    proc.ClientCredentials.ServiceCertificate.DefaultCertificate = proc.ClientCredentials.ClientCertificate.Certificate;

                    // send request now
                    return(proc.runTransaction(requestMessage));
                }
            }
            catch (Exception e)
            {
                if (logger != null)
                {
                    logger.LogException(e);
                }
                if (proc != null)
                {
                    proc.Abort();
                }
                throw;
            }
            finally
            {
                if (proc != null)
                {
                    proc.Close();
                }
            }
        }
Exemple #9
0
    static void Main(string[] args)
    {
        RequestMessage request = new RequestMessage();

        request.merchantID = MERCHANT_ID;

        // Before using this example, replace the generic value with your
        // reference number for the current transaction.
        request.merchantReferenceCode = "your_merchant_reference_code";

        // To help us troubleshoot any problems that you may encounter,
        // please include the following information about your application.
        request.clientLibrary        = ".NET WCF";
        request.clientLibraryVersion = Environment.Version.ToString();
        request.clientEnvironment    =
            Environment.OSVersion.Platform +
            Environment.OSVersion.Version.ToString();

        // This section contains a sample transaction request for the authorization
        // service with complete billing, payment card, and purchase (two items) information.
        request.ccAuthService     = new CCAuthService();
        request.ccAuthService.run = "true";

        BillTo billTo = new BillTo();

        billTo.firstName  = "John";
        billTo.lastName   = "Doe";
        billTo.street1    = "1295 Charleston Road";
        billTo.city       = "Mountain View";
        billTo.state      = "CA";
        billTo.postalCode = "94043";
        billTo.country    = "US";
        billTo.email      = "*****@*****.**";
        billTo.ipAddress  = "10.7.111.111";
        request.billTo    = billTo;

        Card card = new Card();

        card.accountNumber   = "4111111111111111";
        card.expirationMonth = "12";
        card.expirationYear  = "2020";
        request.card         = card;

        PurchaseTotals purchaseTotals = new PurchaseTotals();

        purchaseTotals.currency = "USD";
        request.purchaseTotals  = purchaseTotals;

        request.item = new Item[2];

        Item item = new Item();

        item.id         = "0";
        item.unitPrice  = "12.34";
        request.item[0] = item;

        item            = new Item();
        item.id         = "1";
        item.unitPrice  = "56.78";
        request.item[1] = item;

        try
        {
            TransactionProcessorClient proc = new TransactionProcessorClient();

            proc.ChannelFactory.Credentials.UserName.UserName
                = request.merchantID;
            proc.ChannelFactory.Credentials.UserName.Password
                = TRANSACTION_KEY;

            ReplyMessage reply = proc.runTransaction(request);

            // To retrieve individual reply fields, follow these examples.
            Console.WriteLine("decision = " + reply.decision);
            Console.WriteLine("reasonCode = " + reply.reasonCode);
            Console.WriteLine("requestID = " + reply.requestID);
            Console.WriteLine("requestToken = " + reply.requestToken);
            Console.WriteLine("ccAuthReply.reasonCode = " + reply.ccAuthReply.reasonCode);
        }
        catch (TimeoutException e)
        {
            Console.WriteLine("TimeoutException: " + e.Message + "\n" + e.StackTrace);
        }
        catch (FaultException e)
        {
            Console.WriteLine("FaultException: " + e.Message + "\n" + e.StackTrace);
        }
        catch (CommunicationException e)
        {
            Console.WriteLine("CommunicationException: " + e.Message + "\n" + e.StackTrace);
        }
    }