Exemplo n.º 1
0
 /// <summary>
 /// Gets the purchase totals.
 /// </summary>
 /// <returns></returns>
 private PurchaseTotals GetTotals()
 {
     // paymentInfo not used here since fixed payment installments not implemented
     PurchaseTotals purchaseTotals = new PurchaseTotals();
     purchaseTotals.currency = "USD";
     return purchaseTotals;
 }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            RequestMessage request = new RequestMessage();

            request.merchantID = MERCHANT_ID;

            // 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 PHP application.
            request.clientLibrary        = ".NET C# WSE";
            request.clientLibraryVersion = LIB_VERSION;
            request.clientEnvironment    =
                Environment.OSVersion.Platform +
                Environment.OSVersion.Version.ToString() + "-CLR" +
                Environment.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
            {
                TransactionProcessorWse proc = new TransactionProcessorWse();
                proc.SetPolicy(POLICY_NAME);
                proc.SetClientCredential <UsernameToken>(new UsernameToken(request.merchantID, TRANSACTION_KEY, PasswordOption.SendPlainText));

                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 (SoapHeaderException e)
            {
                Console.WriteLine("SoapHeaderException: " + e.Message + "\n" + e.StackTrace);
            }
            catch (SoapException e)
            {
                Console.WriteLine("SoapException: " + e.Message + "\n" + e.StackTrace);
            }
            catch (WebException e)
            {
                Console.WriteLine("WebException: " + e.Message + "\n" + e.StackTrace);
            }
        }
Exemplo n.º 3
0
        public models.TransactionResponse Refund(models.Profile profile, string originalTranactionId, models.TransactionRequest transactionRequest)
        {
            using (log4net.NDC.Push("Refund::"))
            {
                var merchantId = GetMerchantId(profile);
                var transactionKey = GetTransactionKey(profile);
                var serviceEndPoint = GetServiceEndPoint(profile);

                var request = CreateRequest();
                request.merchantID = merchantId;
                request.merchantReferenceCode = transactionRequest.ReferenceNumber;

                request.ccCreditService = new CCCreditService();
                request.ccCreditService.run = "true";
                request.ccCreditService.captureRequestID = originalTranactionId;
                request.ccCreditService.purchasingLevel = "3";

                PurchaseTotals purchaseTotals = new PurchaseTotals();
                purchaseTotals.currency = transactionRequest.Currency;
                purchaseTotals.grandTotalAmount = FormatPrice(transactionRequest.Amount);
                request.purchaseTotals = purchaseTotals;

                request.invoiceHeader = new InvoiceHeader { userPO = transactionRequest.CustomerPO };
                request.purchaseTotals.dutyAmount = "0.00";
                request.purchaseTotals.discountAmount = "0.00";

                request.invoiceHeader = new InvoiceHeader { userPO = transactionRequest.CustomerPO };
                request.purchaseTotals.dutyAmount = "0.00";
                request.purchaseTotals.discountAmount = "0.00";

                if (transactionRequest.ShipTo != null)
                {
                    request.shipTo = new ShipTo
                    {
                        city = transactionRequest.ShipTo.City,
                        country = transactionRequest.ShipTo.Country,
                        email = transactionRequest.ShipTo.EmailAddress,
                        firstName = transactionRequest.ShipTo.FirstName,
                        lastName = transactionRequest.ShipTo.LastName,
                        postalCode = transactionRequest.ShipTo.PostalCode,
                        state = transactionRequest.ShipTo.State,
                        street1 = transactionRequest.ShipTo.StreetLine1,
                        street2 = transactionRequest.ShipTo.StreetLine2,
                    };
                }
                if (transactionRequest.ShipFrom != null)
                {
                    request.shipFrom = new ShipFrom
                    {
                        country = transactionRequest.ShipFrom.Country,
                        email = transactionRequest.ShipFrom.EmailAddress,
                        firstName = transactionRequest.ShipFrom.FirstName,
                        lastName = transactionRequest.ShipFrom.LastName,
                        postalCode = transactionRequest.ShipFrom.PostalCode,
                        state = transactionRequest.ShipFrom.State,
                        street1 = transactionRequest.ShipFrom.StreetLine1,
                        street2 = transactionRequest.ShipFrom.StreetLine2,
                    };
                }
                if (transactionRequest.LineItems != null)
                {
                    List<Item> items = new List<Item>();
                    foreach (var i in transactionRequest.LineItems)
                    {
                        items.Add(new Item
                        {
                            productCode = i.ProductCode,
                            productName = i.ProductName,
                            productSKU = i.ProductSKU,
                            productDescription = i.ProductDescription,
                            unitPrice = FormatPrice(i.UnitPrice),
                            quantity = i.Quantity.ToString(),
                            taxRate = i.TaxRate.ToString(),
                            taxAmount = FormatPrice(i.TaxAmount),
                            discountAmount = FormatPrice(i.DiscountAmount),
                            totalAmount = FormatPrice(i.UnitPrice),
                            commodityCode = i.CommodityCode,
                            unitOfMeasure = "EA",
                        });
                    }

                    request.item = items.ToArray();
                }
                var client = GetCybersourceService(serviceEndPoint, merchantId, transactionKey);

                _logger.Info("\r\nrequest:" + request.ToJSON());
                var reply = client.runTransaction(request);
                _logger.Info("\r\nreply:" + reply.ToJSON());

                return ProcessReply(profile, reply);
            }
        }
Exemplo n.º 4
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 = "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);
        }
    }
        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));
        }
Exemplo n.º 6
0
    static private String sqlStr = Connection.GetConnectionString("Default", ""); // Controlled by Web Config ARC_Live | ARC_Stage
    /// <summary>
    /// Perform a Follow On Refund
    /// This is based on the user selecting this method
    /// We still validate it; but if the validation fails we just let the user know
    /// </summary>
    /// <param name="cybid">Cybersource Log Auth ID</param>
    /// <param name="amount">Refund Amount</param>
    /// <param name="reason">Refund Reason ID</param>
    /// <param name="reasonnote">Refund Reason Note</param>
    /// <returns></returns>
    #region Processing - Refunds
    static public cybProcess cybRefundFollowOn(int cybid, double amount, string reason, string reasonnotes, System.Web.UI.WebControls.Label lbl)
    {
        cybProcess cybProc = new cybProcess();
        ARC_Cybersource_Log_Refund arcRecord = new ARC_Cybersource_Log_Refund();

        arcRecord.CBAuthID          = cybid;
        arcRecord.RefundReason      = reason;
        arcRecord.RefundReasonNotes = reasonnotes;

        cybProc.message = "processing...";

        #region Process Refund
        try
        {
            /// <summary>
            /// Follow-On transactions only need the RequestID, Token, and Amount of the refund
            /// </summary
            ///
            bool doRefund = false;
            int  callid   = 0;
            #region Initiliaze
            RequestMessage request = new RequestMessage();
            #endregion Initiliaze
            #region Get the SQL Record
            #region SqlConnection
            using (SqlConnection con = new SqlConnection(sqlStr))
            {
                #region SqlCommand cmd
                using (SqlCommand cmd = new SqlCommand("", con))
                {
                    #region Populate the SQL Command
                    cmd.CommandTimeout = 600;
                    #region Build cmdText
                    String cmdText = "";
                    cmdText += @"
-- Did this for recurring transactions which are linked differently
IF EXISTS(
		SELECT TOP 1 1
		FROM [dbo].[cybersource_log_auth] [cb] WITH(NOLOCK)
		JOIN [dbo].[donationccinfo] [di] WITH(NOLOCK) ON [di].[id] = [cb].[externalid]
		JOIN [dbo].[callinfo] [ci] WITH(NOLOCK) ON [ci].[callid] = [di].[callid]
		WHERE 1=1
		AND [cb].[id] = @sp_cybid
)
BEGIN
    SELECT
    [cb].[id]
    ,[cb].[status]
    ,[cb].[createdate]
    ,[cb].[requestid]
    ,[cb].[requesttoken]
    ,[cb].[merchantreferencecode]
    ,[di].[callid]
    ,[cb].[externalid]
    ,[di].[donationamount] [amount]
    ,(SELECT SUM([cr].[cccreditreply_amount]) FROM [dbo].[cybersource_log_refund] [cr] WITH(NOLOCK) WHERE [cr].[externalid] = [di].[id] AND [cr].[reasoncode] = '100') [amount_ref]

    ,[di].[ccnum]
    ,[di].[ccexpmonth]
    ,[di].[ccexpyear]
    ,[ci].[fname]
    ,[ci].[lname]
    ,[ci].[address]
    ,[ci].[suitenumber]
    ,[ci].[zip]
    ,[ci].[city]
    ,[ci].[state]

    ,[cb].[source]
    ,[cb].[decision]
    ,[cb].[reasoncode]
    ,[cb].[ccauthreply_amount]
    ,[cb].[cccapturereply_amount]
    ,[cb].[cccontent]
    FROM [dbo].[cybersource_log_auth] [cb] WITH(NOLOCK)
    JOIN [dbo].[donationccinfo] [di] WITH(NOLOCK) ON [di].[id] = [cb].[externalid]
    JOIN [dbo].[callinfo] [ci] WITH(NOLOCK) ON [ci].[callid] = [di].[callid]
    WHERE 1=1
    AND [cb].[id] = @sp_cybid
END
ELSE
BEGIN

    SELECT
    [cb].[id]
    ,[cb].[status]
    ,[cb].[createdate]
    ,[cb].[requestid]
    ,[cb].[requesttoken]
    ,[cb].[merchantreferencecode]
    ,[di].[callid]
    ,[cb].[externalid]
    ,[di].[donationamount] [amount]
    ,(SELECT SUM([cr].[cccreditreply_amount]) FROM [dbo].[cybersource_log_refund] [cr] WITH(NOLOCK) WHERE [cr].[externalid] = [di].[id] AND [cr].[reasoncode] = '100') [amount_ref]

    ,[di].[ccnum]
    ,[di].[ccexpmonth]
    ,[di].[ccexpyear]
    ,[ci].[fname]
    ,[ci].[lname]
    ,[ci].[address]
    ,[ci].[suitenumber]
    ,[ci].[zip]
    ,[ci].[city]
    ,[ci].[state]

    ,[cb].[source]
    ,[cb].[decision]
    ,[cb].[reasoncode]
    ,[cb].[ccauthreply_amount]
    ,[cb].[cccapturereply_amount]
    ,[cb].[cccontent]
    FROM [dbo].[cybersource_log_auth] [cb] WITH(NOLOCK)
	JOIN [dbo].[donation_recurring_log] [drl] WITH(NOLOCK) ON [drl].[recurringid] = [cb].[externalid]
    JOIN [dbo].[donationccinfo] [di] WITH(NOLOCK) ON [di].[id] = [drl].[donationid]
    JOIN [dbo].[callinfo] [ci] WITH(NOLOCK) ON [ci].[callid] = [di].[callid]
    WHERE 1=1
    AND [cb].[id] = @sp_cybid
END
";
                    #endregion Build cmdText
                    cmd.CommandText = cmdText;
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.Clear();
                    #endregion Populate the SQL Command
                    #region Populate the SQL Params
                    cmd.Parameters.Add(new SqlParameter("@sp_cybid", cybid));
                    #endregion Populate the SQL Params
                    #region Process SQL Command - Try
                    try
                    {
                        if (con.State == ConnectionState.Closed)
                        {
                            con.Open();
                        }
                        using (SqlDataReader sqlRdr = cmd.ExecuteReader())
                        {
                            if (sqlRdr.HasRows)
                            {
                                while (sqlRdr.Read())
                                {
                                    // Ensure we have a valid record for [Follow On]
                                    //cybProc.message = "sql record..." + sqlRdr["status"].ToString();
                                    DateTime dtChargeDate;
                                    DateTime.TryParse(sqlRdr["createdate"].ToString(), out dtChargeDate);
                                    Int32 foLimit = 59; // Days that a Follow On Credit can be performed
                                    callid = Convert.ToInt32(sqlRdr["callid"].ToString());
                                    arcRecord.ExternalID = Convert.ToInt32(sqlRdr["externalid"].ToString());
                                    if (sqlRdr["status"].ToString() == "Settled")
                                    {
                                        // We're good, don't do anything?
                                    }
                                    else if (sqlRdr["status"].ToString() == "Cancelled" && sqlRdr["decision"].ToString() == "ACCEPT")
                                    {
                                        // We're good, don't do anything?
                                    }
                                    else if (sqlRdr["status"].ToString() == "Refunded")
                                    {
                                        // We did this validation, just need to do it again because AGENTS
                                        double dvAmount    = 0;
                                        double dvAmountRef = 0;
                                        Double.TryParse(sqlRdr["amount_ref"].ToString(), out dvAmountRef);
                                        if (dvAmountRef > 0)
                                        {
                                            Double.TryParse(sqlRdr["amount"].ToString(), out dvAmount);
                                            if (dvAmount > 0)
                                            {
                                                if ((dvAmount - dvAmountRef) > 0)
                                                {
                                                    dvAmount = dvAmount - dvAmountRef;
                                                    if (dvAmount >= amount)
                                                    {
                                                        doRefund = true;
                                                    }
                                                }
                                            }
                                        }
                                        if (!doRefund)
                                        {
                                            throw new Exception("Invalid Donation/Refund Amounts");
                                        }
                                    }
                                    else
                                    {
                                        throw new Exception("Invalid Donation Status");
                                    }
                                    if (dtChargeDate != null && (DateTime.UtcNow - dtChargeDate).TotalDays < foLimit)
                                    {
                                        // We're good, don't do anything?
                                    }
                                    else
                                    {
                                        cybProc.message  = "Error:";
                                        cybProc.message += "<br />cybid: " + cybid.ToString();
                                        cybProc.message += "<br />Charge Date: " + dtChargeDate.ToString();
                                        cybProc.message += "<br />";
                                        doRefund         = false;
                                        throw new Exception("Invalid Donation Date");
                                    }
                                    // Add the required data to the request
                                    request.ccCreditService     = new CCCreditService();
                                    request.ccCreditService.run = "true";

                                    request.ccCreditService.captureRequestID    = sqlRdr["requestid"].ToString().Trim();
                                    request.ccCreditService.captureRequestToken = sqlRdr["requesttoken"].ToString().Trim();
                                    request.merchantReferenceCode = sqlRdr["merchantreferencecode"].ToString().Trim();

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

                                    doRefund = true;
                                }
                            }
                            else
                            {
                                cybProc.message = "sql No records...";
                            }
                        }
                    }
                    #endregion Process SQL Command - Try
                    #region Process SQL Command - Catch
                    catch (Exception ex)
                    {
                        cybProc.message += "sql error";
                        ErrorLog.ErrorLog_Display(ex, "DoRefund - Follow On", lbl);
                    }
                    #endregion Process SQL Command - Catch
                }
                #endregion SqlCommand cmd
            }
            #endregion SqlConnection

            #endregion Get the SQL Record
            #region Processing CyberSource Attempt
            if (doRefund)
            {
                //ReplyMessage reply = SoapClient.RunTransaction(request);
                //string template = GetTemplate(reply.decision.ToUpper());
                //string content = GetContent(reply);
                Process_Record_Refund(arcRecord, request, lbl);
                cybProc.status   = arcRecord.Status;
                cybProc.message += "<br />process complete";
            }
            else
            {
            }
            #endregion Processing CyberSource Attempt
        }
        catch (Exception ex)
        {
            cybProc.message = "error";
            ErrorLog.ErrorLog_Display(ex, "DoRefund - Follow On", lbl);
        }
        finally
        {
            //InstantEmail_RefundReport();
        }
        #endregion


        return(cybProc);
    }
Exemplo n.º 7
0
    static public cybProcess cybCharge(ARC_Cybersource_Charge donor)
    {
        cybProcess cybProc = new cybProcess();

        cybProc.status  = "START";
        cybProc.message = "begin processing...";

        #region Insert: CYBERSOURCE
        Boolean doCyberSource    = true;  // [false] Prevents CS from processing (DeBug)
        Boolean donationApproved = false; // Determine if this is the proper place for this, it is used to determine success/failure
        String  ResponseSQL      = "";    // Determien proper place for this, it was a label
        String  cdChargeStatus   = "";    // Determien proper place for this, it was a label

        #region CS Request Creation and Type
        RequestMessage request = new RequestMessage();
        request.ccAuthService        = new CCAuthService();
        request.ccAuthService.run    = "true";
        request.ccCaptureService     = new CCCaptureService();
        request.ccCaptureService.run = "true";
        #endregion CS Request Creation and Type
        #region CS Reconcilliation ID
        /// Reconcilliation ID from ExternalID / DonationCCInfo.ID
        string reconciliationID = donor.donationid.ToString(); // sp_donationccinfoid.ToString();
        // Padding Not Used [Used in IVR/Recurring Services ???]
        //int pad = 16; // 9 for AmEx, 16 for others
        //if (sp_ccnum.StartsWith("3")) { pad = 9; }
        //reconciliationID = reconciliationID.PadRight(pad, '0');
        request.ccAuthService.reconciliationID    = reconciliationID;
        request.ccCaptureService.reconciliationID = reconciliationID;
        request.merchantReferenceCode             = donor.orderid; // sp_orderid = sp_donationccinfoid.ToString().PadLeft(14, '0');;
        #endregion CS Reconcilliation ID
        #region CS billTo
        /// We need to enter default data if non is supplied
        /// We also need to parse the Zip Code against the Zip database
        BillTo billTo = new BillTo();
        billTo.firstName  = donor.billto_firstname; // tb7_first_name.Text.Trim();
        billTo.lastName   = donor.billto_lastname;  // tb7_last_name.Text.Trim();
        billTo.street1    = donor.billto_streeet1;  // tb8_address1.Text.Trim();
        billTo.postalCode = donor.billto_zip;       // tb8_postal_code.Text.Trim();
        billTo.city       = donor.billto_city;      // tb8_city.Text.Trim();
        billTo.state      = donor.billto_state;     // sp_state; // tb8_state.SelectedValue;
        billTo.country    = donor.billto_country;   // sp_country; // "US";
        billTo.email      = donor.billto_email;     // tb8_email.Text.Trim()
        request.billTo    = billTo;
        #endregion CS billTo
        #region CS Card
        Card card = new Card();
        card.accountNumber   = donor.card_number; // sp_ccnum;
        card.expirationMonth = donor.card_month;  // tb7_card_month.SelectedValue;
        card.expirationYear  = donor.card_year;   // tb7_card_year.SelectedValue;
        request.card         = card;
        #endregion CS Card
        #region CS Item / Amount
        PurchaseTotals purchaseTotals = new PurchaseTotals();
        purchaseTotals.currency = "USD";
        request.purchaseTotals  = purchaseTotals;
        request.item            = new Item[1];
        Item item = new Item();
        item.id          = "0";
        item.unitPrice   = donor.amount.ToString(); // sp_donationamount.ToString();
        item.productSKU  = donor.product_sku;       //"DN001";
        item.productName = donor.product_name;      //"ARC Agent Script Donation";
        request.item[0]  = item;
        #endregion CS Item / Amount
        #region CS Process / Reply
        ARC_Cybersource_Log_Auth arcRecord = new ARC_Cybersource_Log_Auth();
        arcRecord.ExternalID = donor.donationid.ToString(); // sp_donationccinfoid.ToString();
        if (doCyberSource)
        {
            try
            {
                ReplyMessage reply    = SoapClient.RunTransaction(request);
                string       template = GetTemplate(reply.decision.ToUpper());
                string       content  = "";
                try { content = GetContent(reply); }
                catch { content = "error"; }
                //Log(logRecord + ",CB: " + String.Format(template, content), "record");
                #region Populate the ARC Record
                if (reply.decision == "ACCEPT")
                {
                    arcRecord.Status = "Settled"; donationApproved = true;
                }
                // Change me before launching Monday !!!!
                //else if (reply.decision == "REJECT" && sp_ccnum == "4111111111111111x" && tglMode == "Stage") { arcRecord.Status = "Settled"; donationApproved = true; }
                else if (reply.decision == "REJECT")
                {
                    arcRecord.Status = "Declined"; donationApproved = false;
                }
                else
                {
                    arcRecord.Status = "Error"; donationApproved = false;
                }


                ResponseSQL += "<br /><b>CS Status: " + arcRecord.Status + "</b>";

                arcRecord.ccContent             = content;
                arcRecord.decision              = reply.decision;
                arcRecord.merchantReferenceCode = reply.merchantReferenceCode;
                try
                {
                    arcRecord.reasonCode = Convert.ToInt32(reply.reasonCode);
                }
                catch { }
                arcRecord.requestID    = reply.requestID;
                arcRecord.requestToken = reply.requestToken;
                #region reply.ccAuthReply
                if (reply.ccAuthReply != null)
                {
                    arcRecord.ccAuthReply_accountBalance = reply.ccAuthReply.accountBalance;
                    //arcRecord.ccAuthReply_accountBalanceCurrency = String.Empty;
                    //arcRecord.ccAuthReply_accountBalanceSign = String.Empty;
                    arcRecord.ccAuthReply_amount            = reply.ccAuthReply.amount;
                    arcRecord.ccAuthReply_authFactorCode    = reply.ccAuthReply.authFactorCode;
                    arcRecord.ccAuthReply_authorizationCode = reply.ccAuthReply.authorizationCode;
                    if (reply.ccAuthReply.authorizedDateTime != null)
                    {
                        arcRecord.ccAuthReply_authorizedDateTime = reply.ccAuthReply.authorizedDateTime.Replace("T", " ").Replace("Z", "");
                    }
                    arcRecord.ccAuthReply_avsCode    = reply.ccAuthReply.avsCode;
                    arcRecord.ccAuthReply_avsCodeRaw = reply.ccAuthReply.avsCodeRaw;
                    //arcRecord.ccAuthReply_cardCategory = String.Empty;
                    arcRecord.ccAuthReply_cavvResponseCode    = reply.ccAuthReply.cavvResponseCode;
                    arcRecord.ccAuthReply_cavvResponseCodeRaw = reply.ccAuthReply.cavvResponseCodeRaw;
                    arcRecord.ccAuthReply_cvCode                = reply.ccAuthReply.cvCode;
                    arcRecord.ccAuthReply_cvCodeRaw             = reply.ccAuthReply.cvCodeRaw;
                    arcRecord.ccAuthReply_merchantAdviceCode    = reply.ccAuthReply.merchantAdviceCode;
                    arcRecord.ccAuthReply_merchantAdviceCodeRaw = reply.ccAuthReply.merchantAdviceCodeRaw;
                    //arcRecord.ccAuthReply_ownerMerchantID = String.Empty;
                    //arcRecord.ccAuthReply_paymentNetworkTransactionID = String.Empty;
                    arcRecord.ccAuthReply_processorResponse = reply.ccAuthReply.processorResponse;
                    try
                    {
                        arcRecord.ccAuthReply_reasonCode = Convert.ToInt32(reply.ccAuthReply.reasonCode);
                    }
                    catch { }
                    arcRecord.ccAuthReply_reconciliationID       = reply.ccAuthReply.reconciliationID;
                    arcRecord.ccAuthReply_referralResponseNumber = String.Empty;
                    arcRecord.ccAuthReply_requestAmount          = donor.amount.ToString(); // sp_donationamount.ToString();
                    arcRecord.ccAuthReply_requestCurrency        = String.Empty;
                }
                #endregion reply.ccAuthReply
                #region reply.ccCaptureReply
                if (reply.ccCaptureReply != null)
                {
                    arcRecord.ccCaptureReply_amount = reply.ccCaptureReply.amount;
                    try
                    {
                        arcRecord.ccCaptureReply_reasonCode = Convert.ToInt32(reply.ccCaptureReply.reasonCode);
                    }
                    catch { }
                    arcRecord.ccCaptureReply_reconciliationID = reply.ccCaptureReply.reconciliationID;
                    arcRecord.ccCaptureReply_requestDateTime  = reply.ccCaptureReply.requestDateTime.Replace("T", " ").Replace("Z", "");
                }
                #endregion reply.ccCaptureReply

                #endregion Populate the ARC Record
                cdChargeStatus = arcRecord.Status;
                cybProc.status = arcRecord.Status;
            }
            catch (Exception ex)
            {
                // Depending on the type of error, the user may be able to re-try, or this may be a fatal failure
                cybProc.status     = "ERROR";
                cybProc.message    = "cybCharge - Catch - doCyberSource";
                cybProc.lblmessage = ErrorLog.ErrorLog_Display_String(ex, "Error: Processing Donation 002");
            }
        }
        else
        {
            // Declined - Not Processed
            donationApproved = false;
            arcRecord.Status = "Declined";
            cdChargeStatus   = arcRecord.Status;
            cybProc.status   = arcRecord.Status;
        }
        #endregion CS Process / Reply
        #region CS Insert SQL
        #region Save the record to SQL
        if (arcRecord.Status != null)
        {
            //arcRecord.Source = "PORTAL";
            //arcRecord.Source = "WEB"; // Get this from the record type
            //arcRecord.Source = "IVR";
            //arcRecord.Source = "RECURRING";
            arcRecord.Source = donor.source;
            ARC_Cybersource_To_SQL(arcRecord, cybProc);
        }
        #endregion Save the record to SQL
        #endregion CS Insert SQL
        #endregion Insert: CYBERSOURCE
        return(cybProc);
    }
        static void Main(string[] args)
        {
            RequestMessage request = new RequestMessage();

            // we will let the client pick up the merchantID
            // from the config file.  In multi-merchant scenarios,
            // you would set a merchantID in each request.

            // this sample requests auth and capture

            // Credit Card Authorization
            request.ccAuthService     = new CCAuthService();
            request.ccAuthService.run = "true";

            // Credit Card Capture
            request.ccCaptureService     = new CCCaptureService();
            request.ccCaptureService.run = "true";


            // add required fields

            request.merchantReferenceCode = "your_merchant_reference_code";

            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;

            // there are two items in this sample
            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;

            // add optional fields here per your business needs

            try
            {
                ReplyMessage reply = SoapClient.RunTransaction(request);
                SaveOrderState();
                ProcessReply(reply);
            }

            /*** There are many specific exceptions that could be caught here. Only a few are provided as examples.
             * This is a Windows Communication Foundation (WCF) Client and uses exceptions from the System.ServiceModel
             * Namespaces. Please refer to the Microsoft documentation to better understand what these exceptions mean.
             *
             ***/

            //System.ServiceModel Exception examples.
            catch (EndpointNotFoundException e)
            {
                // This is thrown when a remote endpoint could not be found or reached.
                // The remote endpoint is down, the client network connection is down,
                // the remote endpoint is unreachable, or because the remote network is unreachable.

                SaveOrderState();
                HandleException(e);
            }
            catch (ChannelTerminatedException e)
            {
                // This is typically thrown on the client when a channel is terminated due to the server closing the connection.
                SaveOrderState();
                HandleException(e);
            }
            //System.ServiceModel.Security Exception example.
            catch (MessageSecurityException e)
            {
                //Represents an exception that occurred when there is something wrong with the security applied on a message. Possibly a bad signature.
                SaveOrderState();
                HandleSecurityException(e);
            }
            //System.Security.Cryptography exception
            catch (CryptographicException ce)
            {
                //Represents a problem with your X509 certificate (.p12 file) or a problem creating a signature from the certificate.
                SaveOrderState();
                HandleCryptoException(ce);
            }
            //System.Net exception
            catch (WebException we)
            {
                //The WebException class is thrown by classes descended from WebRequest and WebResponse that implement pluggable protocols for accessing the Internet.
                SaveOrderState();
                HandleWebException(we);
            }
            //Any other exception!
            catch (Exception e)
            {
                SaveOrderState();
                HandleException(e);
            }

            Console.WriteLine("Press Return to end...");
            Console.ReadLine();
        }
Exemplo n.º 9
0
    protected void ProcessRefund_FollowOn()
    {
        WriteToLabel("add", "Red", "<br />" + "Processing: Follow-On Transaction - Start", dtlLabel);
        #region Process Refund
        try
        {
            /// <summary>
            /// Follow-On transactions only need the RequestID, Token, and Amount of the refund
            /// </summary
            #region Processing CyberSource Attempt
            RequestMessage request = new RequestMessage();
            request.ccCreditService     = new CCCreditService();
            request.ccCreditService.run = "true";

            DateTime dtChargeDate;
            DateTime.TryParse(CreateDate.Text, out dtChargeDate);
            if (dtChargeDate == null)
            {
                // Throw an Exception since the date is not valid
                throw new Exception("Invalid Donation Date");
            }
            //dtlLabel.Text = (dtChargeDate - DateTime.UtcNow).TotalDays.ToString();
            #region Stand-Alone Credit
            if ((DateTime.UtcNow - dtChargeDate).TotalDays > foLimit)
            {
                // Stand Alone
                BillTo billTo = new BillTo();
                billTo.firstName  = FirstName.Text;
                billTo.lastName   = LastName.Text;
                billTo.street1    = Address1.Text;
                billTo.postalCode = Zip.Text;
                billTo.city       = City.Text;
                billTo.state      = ddlState.Text;
                billTo.country    = ddlCountry.Text;

                billTo.email = "*****@*****.**";

                request.billTo = billTo;

                Card card = new Card();
                card.accountNumber   = CardNumberFull.Value;
                card.expirationMonth = CardMonth.Text;
                card.expirationYear  = CardYear.Text;
                if (CardTypeFull.Value.Length > 0)
                {
                    card.cardType = CardTypeFull.Value;
                }
                request.card = card;
            }
            #endregion Stand-Alone Credit
            #region Follow On Credit
            else
            {
                // Follow On
                // Credit Required Fields
                request.ccCreditService.captureRequestID    = RequestID.Text.Trim();
                request.ccCreditService.captureRequestToken = RequestToken.Text.Trim();
            }
            #endregion Follow On Credit


            request.merchantReferenceCode = ReferenceNum.Text.Trim();

            PurchaseTotals purchaseTotals = new PurchaseTotals();
            purchaseTotals.currency         = "USD";
            purchaseTotals.grandTotalAmount = Amount.Text.Trim();
            request.purchaseTotals          = purchaseTotals;

            //Attempt processing the request, handle excepts
            Console.WriteLine("     ");
            WriteToLabel("add", "Red", "<br />" + "Sending Request", dtlLabel);
            #endregion Processing CyberSource Attempt
            #region RunTransaction: Try
            try
            {
                ARC_Cybersource_Log_Refund arcRecord = new ARC_Cybersource_Log_Refund();

                ReplyMessage reply = SoapClient.RunTransaction(request);

                string template = GetTemplate(reply.decision.ToUpper());
                string content  = GetContent(reply);
                lblTemplate.Text     = String.Format(template, content);
                arcRecord.ccContent  = content;
                arcRecord.ExternalID = lblExternalID.Text;
                arcRecord.CBAuthID   = lblCBAuthID.Text;

                if (reply.decision == "ACCEPT")
                {
                    arcRecord.Status = "Refunded";
                }
                else if (reply.decision == "REJECT")
                {
                    arcRecord.Status = "Rejected";
                }
                else
                {
                    arcRecord.Status = "Error";
                }


                arcRecord.decision = reply.decision;
                arcRecord.merchantReferenceCode = reply.merchantReferenceCode;
                arcRecord.reasonCode            = reply.reasonCode;
                arcRecord.requestID             = reply.requestID;
                arcRecord.requestToken          = reply.requestToken;
                if (reply.ccCreditReply != null)
                {
                    arcRecord.ccCreditReply_amount           = (reply.ccCreditReply.amount != null) ? arcRecord.ccCreditReply_amount = reply.ccCreditReply.amount : "0";
                    arcRecord.ccCreditReply_reasonCode       = (reply.ccCreditReply.reasonCode != null) ? reply.ccCreditReply.reasonCode : "";
                    arcRecord.ccCreditReply_reconciliationID = (reply.ccCreditReply.reconciliationID != null) ? reply.ccCreditReply.reconciliationID : "";
                    arcRecord.ccCreditReply_requestDateTime  = (reply.ccCreditReply.requestDateTime != null) ? reply.ccCreditReply.requestDateTime.Replace("T", " ").Replace("Z", "") : "";
                }
                //ProcessRefund_SQLUpdate()

                rplDecision.Text = arcRecord.decision;
                rplMerchantReferenceCode.Text = arcRecord.merchantReferenceCode;
                rplReasonCode.Text            = arcRecord.reasonCode;
                rplRequestID.Text             = arcRecord.requestID;
                rplRequestToken.Text          = arcRecord.requestToken;

                rplAmount.Text                = arcRecord.ccCreditReply_amount;
                rplReasonCode2.Text           = arcRecord.ccCreditReply_reasonCode;
                rplReconciliationID.Text      = arcRecord.ccCreditReply_reconciliationID;
                rplReconciliationID.ForeColor = System.Drawing.Color.Blue;
                rplReconciliationID.Font.Bold = true;
                rplRequestDateTime.Text       = arcRecord.ccCreditReply_requestDateTime;

                Record_Save(arcRecord);
                Record_Get(Convert.ToInt32(Request["cbid"]));
            }
            #endregion RunTransaction: Try
            #region RunTransaction: Catch
            catch (Exception ex)
            {
                msgLabel.Text    = "Oops";
                rplDecision.Text = "!! ERROR - NOT COMPLETED !!";
                msgRefund        = ex.Message;
                Error_Save(ex, "RunTransaction");
            }
            #endregion RunTransaction: Catch
        }
        catch (Exception ex)
        {
            msgLabel.Text    = "Oops";
            rplDecision.Text = "!! ERROR - NOT COMPLETED !!";
            msgRefund        = ex.Message;
            Error_Save(ex, "Processing_CyberSource");
        }
        finally
        {
            InstantEmail_RefundReport();
        }
        #endregion
        WriteToLabel("add", "Red", "<br />" + "Processing: Follow-On Transaction - End", dtlLabel);
    }
Exemplo n.º 10
0
    private void Authorize(ref CreditCard card1)
    {
        try
        {
            // create request object
            RequestMessage request = new RequestMessage();
            BillTo         billTo  = new BillTo();
            configure();
            // add general fields
            if (!(null == Session["OrderNumber"]))
            {
                request.merchantReferenceCode = (string)Session["OrderNumber"];
            }

            request.ccAuthService     = new CCAuthService();
            request.ccAuthService.run = "true";

            // add purchasing info
            PurchaseTotals purchaseTotals = new PurchaseTotals();
            purchaseTotals.currency = "USD";
            request.purchaseTotals  = purchaseTotals;

            // add shopper info
            Shopper shopper = (Shopper)Session["Shopper"];
            Global1.AddShopperFields(ref billTo, shopper);
            request.billTo = billTo;

            //add item info
            Items items = (Items)Session["ShoppingCart"];
            Global1.AddItemFields(ref request, items);

            // add card info
            Card card = new Card();
            card.accountNumber   = card1.accountNumber;
            card.expirationMonth = card1.expirationMonth;
            card.expirationYear  = card1.expirationYear;
            card.cvNumber        = card1.cvNumber;
            request.card         = card;

            // send request now
            reply = SoapClient.RunTransaction(config, request);
            // process the transaction as per response.
            HandleReply();
        }
        catch (BugException e)
        {
            Session["Exception"] = e;
            HandleReply();
        }
        catch (NonCriticalTransactionException e)
        {
            Session["Exception"] = e;
            HandleReply();
        }
        catch (CriticalTransactionException e)
        {
            // The transaction may have been successfully processed by
            // CyberSource.  Aside from redirecting to an error page, you should
            // make sure that someone gets notified of the occurrence of this
            // exception so that they could check the outcome of the transaction
            // on the CyberSource Support Screens.  For example, you could
            // post an event log or send an email to a monitored address.
            Session["Exception"] = e;
            HandleReply();
        }
    }
Exemplo n.º 11
0
		static void Main(string[] args)
		{
			RequestMessage request = new RequestMessage();

            // we will let the client pick up the merchantID
            // from the config file.  In multi-merchant scenarios,
            // you would set a merchantID in each request.

            // this sample requests auth and capture
	
			// Credit Card Authorization
			request.ccAuthService = new CCAuthService();
			request.ccAuthService.run = "true";

			// Credit Card Capture
			request.ccCaptureService = new CCCaptureService();
			request.ccCaptureService.run = "true";


			// add required fields

			request.merchantReferenceCode = "your_merchant_reference_code";

			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;

			// there are two items in this sample
			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;

			// add optional fields here per your business needs

			try
			{
				ReplyMessage reply = SoapClient.RunTransaction( request );
				SaveOrderState();
				ProcessReply( reply );
			}
           /*** There are many specific exceptions that could be caught here. Only a few are provided as examples. 
             This is a Windows Communication Foundation (WCF) Client and uses exceptions from the System.ServiceModel
             Namespaces. Please refer to the Microsoft documentation to better understand what these exceptions mean.
                
            ***/

           //System.ServiceModel Exception examples.
            catch (EndpointNotFoundException e)
            {
                // This is thrown when a remote endpoint could not be found or reached.  
                // The remote endpoint is down, the client network connection is down, 
                // the remote endpoint is unreachable, or because the remote network is unreachable.

                SaveOrderState();
                HandleException(e);
            }
            catch (ChannelTerminatedException e)
            {
                // This is typically thrown on the client when a channel is terminated due to the server closing the connection.
                SaveOrderState();
                HandleException(e);
            }
            //System.ServiceModel.Security Exception example.
            catch (MessageSecurityException e)
            {
                //Represents an exception that occurred when there is something wrong with the security applied on a message. Possibly a bad signature.
                SaveOrderState();
                HandleSecurityException(e);
            }
            //System.Security.Cryptography exception    
            catch (CryptographicException ce)
            {
                //Represents a problem with your X509 certificate (.p12 file) or a problem creating a signature from the certificate.
                SaveOrderState();
                HandleCryptoException(ce);
            }
            //System.Net exception    
            catch (WebException we)
            {
                //The WebException class is thrown by classes descended from WebRequest and WebResponse that implement pluggable protocols for accessing the Internet.
                SaveOrderState();
                HandleWebException(we);
            }
            //Any other exception!
            catch (Exception e)
            {
                SaveOrderState();
                HandleException(e);
            }

            Console.WriteLine("Press Return to end...");
            Console.ReadLine();
		}
Exemplo n.º 12
0
    protected void CyberSource_Customer_Transaction_Tokenization()
    {
        try
        {
            /// This will create a Transaction using Tokenization as payment
            RequestMessage request = new RequestMessage();
            request.ccAuthService        = new CCAuthService();
            request.ccAuthService.run    = "true";
            request.ccCaptureService     = new CCCaptureService();
            request.ccCaptureService.run = "true";

            string reconciliationID = donationid.Text.ToString();

            request.ccAuthService.reconciliationID    = reconciliationID;
            request.ccCaptureService.reconciliationID = reconciliationID;
            request.merchantReferenceCode             = reconciliationID;

            RecurringSubscriptionInfo SubscriptionInfo = new RecurringSubscriptionInfo();
            SubscriptionInfo.subscriptionID   = subscriptionID.Text; // "4738680334246909704009";
            request.recurringSubscriptionInfo = SubscriptionInfo;

            #region purchaseTotals
            PurchaseTotals purchaseTotals = new PurchaseTotals();
            purchaseTotals.currency = "USD";
            request.purchaseTotals  = purchaseTotals;
            request.item            = new Item[1];
            Item item = new Item();
            item.id          = "0";
            item.unitPrice   = "5.25";
            item.productSKU  = "RD001";
            item.productName = "ARC Tokenization";
            request.item[0]  = item;
            #endregion purchaseTotals

            #region Reply
            ReplyMessage reply    = SoapClient.RunTransaction(request);
            string       template = ghCyberSource.GetTemplate(reply.decision.ToUpper());
            string       content  = "";
            try { content = ghCyberSource.GetContent(reply); }
            catch { content = "error"; }


            #endregion Reply


            txtTemplate.Text = template.ToString();
            txtContent.Text  = content.ToString();
            txtReply.Text    = reply.ToString();
            lblCatch.Text   += String.Format("<br />decision: {0}", reply.decision.ToUpper());
            try { lblCatch.Text += String.Format("<br />reasonCode: {0}", reply.reasonCode); } catch { }
            try { lblCatch.Text += String.Format("<br />merchantReferenceCode: {0}", reply.merchantReferenceCode); } catch { }
            lblCatch.Text += "<hr />";
            try { lblCatch.Text += String.Format("<br />amount: {0}", reply.ccAuthReply.amount); } catch { String.Format("<br />amount: {0}", "x"); }
            try { lblCatch.Text += String.Format("<br />authFactorCode: {0}", reply.ccAuthReply.authFactorCode); } catch { String.Format("<br />authFactorCode: {0}", "x"); }
            try { lblCatch.Text += String.Format("<br />authorizationCode: {0}", reply.ccAuthReply.authorizationCode); } catch { String.Format("<br />authorizationCode: {0}", "x"); }
            try { lblCatch.Text += String.Format("<br />authorizedDateTime: {0}", reply.ccAuthReply.authorizedDateTime); } catch { String.Format("<br />authorizedDateTime: {0}", "x"); }
            try { lblCatch.Text += String.Format("<br />avsCode: {0}", reply.ccAuthReply.avsCode); } catch { String.Format("<br />avsCode: {0}", "x"); }
            try { lblCatch.Text += String.Format("<br />avsCodeRaw: {0}", reply.ccAuthReply.avsCodeRaw); } catch { String.Format("<br />avsCodeRaw: {0}", "x"); }
            try { lblCatch.Text += String.Format("<br />cavvResponseCode: {0}", reply.ccAuthReply.cavvResponseCode); } catch { String.Format("<br />cavvResponseCode: {0}", "x"); }
            try { lblCatch.Text += String.Format("<br />cavvResponseCodeRaw: {0}", reply.ccAuthReply.cavvResponseCodeRaw); } catch { String.Format("<br />cavvResponseCodeRaw: {0}", "x"); }
            try { lblCatch.Text += String.Format("<br />cvCode: {0}", reply.ccAuthReply.cvCode); } catch { String.Format("<br />cvCode: {0}", "x"); }
            try { lblCatch.Text += String.Format("<br />cvCodeRaw: {0}", reply.ccAuthReply.cvCodeRaw); } catch { String.Format("<br />cvCodeRaw: {0}", "x"); }
            try { lblCatch.Text += String.Format("<br />merchantAdviceCode: {0}", reply.ccAuthReply.merchantAdviceCode); } catch { String.Format("<br />merchantAdviceCode: {0}", "x"); }
            try { lblCatch.Text += String.Format("<br />merchantAdviceCodeRaw: {0}", reply.ccAuthReply.merchantAdviceCodeRaw); } catch { String.Format("<br />merchantAdviceCodeRaw: {0}", "x"); }
            try { lblCatch.Text += String.Format("<br />processorResponse: {0}", reply.ccAuthReply.processorResponse); } catch { String.Format("<br />processorResponse: {0}", "x"); }
            try { lblCatch.Text += String.Format("<br />reasonCode: {0}", reply.ccAuthReply.reasonCode); } catch { String.Format("<br />reasonCode: {0}", "x"); }
            try { lblCatch.Text += String.Format("<br />reconciliationID: {0}", reply.ccAuthReply.reconciliationID); } catch { String.Format("<br />reconciliationID: {0}", "x"); }
            lblCatch.Text += "<hr />";
            try { lblCatch.Text += String.Format("<br />missingField: {0}", reply.missingField.Length); } catch { String.Format("<br />missingField: {0}", "x"); }
        }
        catch (Exception ex)
        {
            lblCatch.Text += String.Format("<table class='table_error'>"
                                           + "<tr><td>Error<td/><td>{0}</td></tr>"
                                           + "<tr><td>Message<td/><td>{1}</td></tr>"
                                           + "<tr><td>StackTrace<td/><td>{2}</td></tr>"
                                           + "<tr><td>Source<td/><td>{3}</td></tr>"
                                           + "<tr><td>InnerException<td/><td>{4}</td></tr>"
                                           + "<tr><td>Data<td/><td>{5}</td></tr>"
                                           + "</table>"
                                           , "Tokenization"    //0
                                           , ex.Message        //1
                                           , ex.StackTrace     //2
                                           , ex.Source         //3
                                           , ex.InnerException //4
                                           , ex.Data           //5
                                           , ex.HelpLink
                                           , ex.TargetSite
                                           );
        }
    }