// static constructor
        static ReplyMessageJsonEncoderTests()
        {
            __testMessage = new ReplyMessage<BsonDocument>(__awaitCapable, __cursorId, __cursorNotFound, __documents, __numberReturned, false, null, __requestId, __responseTo, __serializer, __startingFrom);

            __testMessageJson =
                "{ " +
                    "\"opcode\" : \"reply\", " +
                    "\"requestId\" : 1, " +
                    "\"responseTo\" : 2, " +
                    "\"cursorId\" : NumberLong(3), " +
                    "\"numberReturned\" : 2, " +
                    "\"startingFrom\" : 4, " +
                    "\"awaitCapable\" : true, " +
                    "\"documents\" : [{ \"_id\" : 1 }, { \"_id\" : 2 }]" +
                " }";

            __queryFailureMessage = new ReplyMessage<BsonDocument>(false, __cursorId, true, null, 0, true, __queryFailureDocument, __requestId, __responseTo, __serializer, 0);

            __queryFailureMessageJson =
                "{ " +
                    "\"opcode\" : \"reply\", " +
                    "\"requestId\" : 1, " +
                    "\"responseTo\" : 2, " +
                    "\"cursorId\" : NumberLong(3), " +
                    "\"cursorNotFound\" : true, " +
                    "\"numberReturned\" : 0, " +
                    "\"queryFailure\" : { \"ok\" : 0 }" +
               " }";
        }
Ejemplo n.º 2
0
        void IMessageSink.Invoke(ReplyMessage reply)
        {
            if (reply == null) throw new ArgumentNullException("reply");

            MessageEvent outgoingRequest = DAO.For<MessageEvent>().Single(match => match.CorrelationId == reply.CorrelationId
                && match.Kind == MessageEventKind.Request && match.Direction == MessageEventDirection.Outgoing);
            if (outgoingRequest == null)
            {
                throw new InvalidReplyException(String.Format("A corresponding Outgoing Request was never Sent for Incoming Reply '{0}' and Event '{1}'. Reply will be Ignored!"
                    , reply.CorrelationId
                    , reply.Event)
                    , reply);
            }

            MessageEvent incomingReply = DAO.For<MessageEvent>().Single(match => match.CorrelationId == reply.CorrelationId
                && match.Kind == MessageEventKind.Reply && match.Direction == MessageEventDirection.Incoming
                && match.Thumbprint == reply.Thumbprint());
            if (incomingReply != null)
            {
                throw new DuplicateReplyException(String.Format("Incoming Reply '{0}' for Event '{1}' was already processed. Reply will be Ignored!"
                    , reply.CorrelationId
                    , reply.Event)
                    , reply);
            }

            DAO.For<MessageEvent>().Upsert(reply);
        }
Ejemplo n.º 3
0
        private void OnReciveRequestMessage(dynamic request)
        {
            var reply = new ReplyMessage
            {
                ClientName = request.ClientName,
                RequestId = request.RequestId,
                Action = request.Action
            };

            IFileChannelHandler handler;

            object replyResult = null;
            Exception replyError = null;

            if (_handlers.TryGetValue(reply.Action, out handler))
            {
                try
                {
                    replyResult = handler.Handle(request.Arguments);
                    reply.Result = replyResult;
                }
                catch (Exception error)
                {
                    replyError = error;
                    reply.Exception = replyError.Message;
                    reply.IsFaulted = true;
                }

                reply.IsHandled = true;
            }

            _dispatcher.Reply(reply.ClientName, reply);

            if (handler != null)
            {
                if (reply.IsFaulted)
                {
                    try
                    {
                        handler.OnError(request, replyError);
                    }
                    catch
                    {
                    }
                }
                else
                {
                    try
                    {
                        handler.OnSuccess(request, replyResult);
                    }
                    catch
                    {
                    }
                }
            }
        }
Ejemplo n.º 4
0
        void IMessageSink.Invoke(ReplyMessage reply)
        {
            if (reply == null) throw new ArgumentNullException("reply");

            DistributedMessaging messaging = DistributedMessaging.Instance;
            Action<ReplyMessage> eventHandler = messaging.Handlers.Outgoing.Reply(reply.Event);
            if (eventHandler != null)
            {
                eventHandler.DynamicInvoke(reply);
            }
        }
Ejemplo n.º 5
0
 public override void Publish(ReplyMessage reply)
 {
     try
     {
         Write(reply);
     }
     catch (Exception e)
     {
         OnChannelError(e);
     }
 }
Ejemplo n.º 6
0
 public void Constructor_with_cursor_not_found_should_initialize_instance()
 {
     var subject = new ReplyMessage<BsonDocument>(true, _cursorId, true, null, 0, false, null, _requestId, _responseTo, _serializer, 0);
     subject.AwaitCapable.Should().BeTrue();
     subject.CursorId.Should().Be(_cursorId);
     subject.CursorNotFound.Should().BeTrue();
     subject.Documents.Should().BeNull();
     subject.NumberReturned.Should().Be(0);
     subject.QueryFailure.Should().BeFalse();
     subject.QueryFailureDocument.Should().BeNull();
     subject.RequestId.Should().Be(_requestId);
     subject.ResponseTo.Should().Be(_responseTo);
     subject.Serializer.Should().BeSameAs(_serializer);
     subject.StartingFrom.Should().Be(0);
 }
        public string AddReplyMessage(string FromUserId, string Name, string UserId, string MessageId, string Message, string type)
        {
            String status = "Failed";
            try
            {
                ReplyMessageRepository RplyMsgRepository = new ReplyMessageRepository();
                ReplyMessage RplMsg = new ReplyMessage();

                Guid _Id = Guid.NewGuid();
                Guid _UserId = Guid.Parse(UserId);
                Guid _MessageId = Guid.Parse(MessageId);

                RplMsg.Id = _Id;
                RplMsg.FromUserId = FromUserId;
                RplMsg.Name = Name;
                RplMsg.UserId = _UserId;
                RplMsg.MessageId = _MessageId;
                RplMsg.Message = Message;
                RplMsg.Type = type;

                try
                {
                    RplyMsgRepository.AddReplyMessage(RplMsg);
                    status = "Success";
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    status = ex.Message;
                }
            }
            catch (Exception)
            {

            }
            return new JavaScriptSerializer().Serialize(status);
        }
        // static constructor
        static ReplyMessageBinaryEncoderTests()
        {
            __testMessage = new ReplyMessage<BsonDocument>(__awaitCapable, __cursorId, __cursorNotFound, __documents, __numberReturned, false, null, __requestId, __responseTo, __serializer, __startingFrom);

            __testMessageBytes = new byte[]
            {
                0, 0, 0, 0, // messageLength
                1, 0, 0, 0, // requestId
                2, 0, 0, 0, // responseTo
                1, 0, 0, 0, // opcode = 1
                9, 0, 0, 0, // responseFlags
                3, 0, 0, 0, 0, 0, 0, 0, // cursorId
                4, 0, 0, 0, // startingFrom
                2, 0, 0, 0, // numberReturned
                14, 0, 0, 0, 0x10, (byte)'_', (byte)'i', (byte)'d', 0, 1, 0, 0, 0, 0, // documents[0]
                14, 0, 0, 0, 0x10, (byte)'_', (byte)'i', (byte)'d', 0, 2, 0, 0, 0, 0, // documents[1]
            };
            __testMessageBytes[0] = (byte)__testMessageBytes.Length;
            __flagsOffset = 16;

            __queryFailureMessage = new ReplyMessage<BsonDocument>(false, __cursorId, false, null, 0, true, __queryFailureDocument, __requestId, __responseTo, __serializer, 0);

            __queryFailureMessageBytes = new byte[]
            {
                0, 0, 0, 0, // messageLength
                1, 0, 0, 0, // requestId
                2, 0, 0, 0, // responseTo
                1, 0, 0, 0, // opcode = 1
                2, 0, 0, 0, // responseFlags
                3, 0, 0, 0, 0, 0, 0, 0, // cursorId
                0, 0, 0, 0, // startingFrom
                0, 0, 0, 0, // numberReturned
                13, 0, 0, 0, 0x10, (byte)'o', (byte)'k', 0, 0, 0, 0, 0, 0, // queryFailureDocument
            };
            __queryFailureMessageBytes[0] = (byte)__queryFailureMessageBytes.Length;
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Submits the transaction.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        private ReplyMessage SubmitTransaction( FinancialGateway financialGateway, RequestMessage request, out string errorMessage )
        {
            ReplyMessage reply = new ReplyMessage();
            TransactionProcessorClient client = GetProxyClient( financialGateway, out errorMessage );

            // Error message already set, return
            if ( client == null )
            {
                return null;
            }

            try
            {
                reply = client.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;
            }
        }
Ejemplo n.º 10
0
 protected models.TransactionResponse ProcessReply(Profile profile, ReplyMessage reply)
 {
     var response = new models.TransactionResponse();
     response.Status = true;
     response.ReasonCode = reply.reasonCode;
     if (reply.reasonCode != "100")
     {
         response.Status = false;
         response.Message = reply.reasonCode + ". " + Combine(reply.missingField) + Combine(reply.invalidField);
     }
     else
     {
         response.TransactionId = string.Format("p{0}-{1}", profile.ProfileID, reply.requestID);
     }
     return response;
 }
        /// <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 | X509KeyStorageFlags.MachineKeySet);

                    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 | X509KeyStorageFlags.MachineKeySet);

                    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();
                }
            }
        }
Ejemplo n.º 12
0
 public override void ConnectionAfterReceivingMessage <T>(ConnectionId connectionId, ReplyMessage <T> message, int length, TimeSpan elapsed)
 {
     Log(LogLevel.Info, "{0}: received message in response to {1} of length {2} bytes in {3}ms.", Label(connectionId), message.ResponseTo.ToString(), length.ToString(), elapsed.TotalMilliseconds.ToString());
 }
Ejemplo n.º 13
0
        public override String ProcessCard(int OrderNumber, int CustomerID, Decimal OrderTotal, bool useLiveTransactions, TransactionModeEnum TransactionMode, AspDotNetStorefrontCore.Address UseBillingAddress, String CardExtraCode, AspDotNetStorefrontCore.Address UseShippingAddress, String CAVV, String ECI, String XID, out String AVSResult, out String AuthorizationResult, out String AuthorizationCode, out String AuthorizationTransID, out String TransactionCommandOut, out String TransactionResponse)
        {
            AVSResult             = "N/A";
            AuthorizationResult   = "N/A";
            AuthorizationCode     = "N/A";
            AuthorizationTransID  = "N/A";
            TransactionCommandOut = "N/A";
            TransactionResponse   = String.Empty;

            String signedPARes = String.Empty;
            String result      = AppLogic.ro_OK;

            CustomerSession cSession = new CustomerSession(CustomerID);

            if (cSession["3Dsecure.PaRes"].Length != 0)
            {
                signedPARes = cSession["3Dsecure.PaRes"];
                // After grabbing it, clear out the session PaRes so it won't be re-used ever again.
                cSession["3Dsecure.PaRes"] = String.Empty;
            }

            Configuration conf = new Configuration();

            conf.KeysDirectory = AppLogic.AppConfig("CYBERSOURCE.keysDirectory");
            conf.KeyFilename   = AppLogic.AppConfig("CYBERSOURCE.keyFilename");
            conf.MerchantID    = AppLogic.AppConfig("CYBERSOURCE.merchantID");
            conf.ServerURL     = CommonLogic.IIF(useLiveTransactions, AppLogic.AppConfig("CYBERSOURCE.LiveURL"), AppLogic.AppConfig("CYBERSOURCE.TestURL"));
            if (AppLogic.AppConfigBool("CYBERSOURCE.UsePIT"))
            {
                conf.ServerURL = AppLogic.AppConfig("CYBERSOURCE.PITURL");
            }


            RequestMessage request = new RequestMessage();

            request.clientApplication        = "AspDotNetStorefront";
            request.clientApplicationVersion = AppLogic.AppConfig("StoreVersion");
            request.clientApplicationUser    = CustomerID.ToString();

            request.merchantReferenceCode = "Order # " + OrderNumber.ToString() + " " + Localization.ToNativeDateTimeString(System.DateTime.Now);

            int  CardTypeID  = DB.GetSqlN("select CardTypeID N from CreditCardType where CardType = " + DB.SQuote(UseBillingAddress.CardType));
            bool Try3DSecure = CommonLogic.IntegerIsInIntegerList(CardTypeID, AppLogic.AppConfig("3DSECURE.CreditCardTypeIDs"));

            if (Try3DSecure)
            {
                if (signedPARes == String.Empty)
                {
                    request.payerAuthEnrollService     = new PayerAuthEnrollService();
                    request.payerAuthEnrollService.run = "true";
                    if (AppLogic.AppConfig("CYBERSOURCE.paCountryCode") != "")
                    {
                        request.payerAuthEnrollService.countryCode = AppLogic.AppConfig("CYBERSOURCE.paCountryCode");
                    }
                    if (AppLogic.AppConfig("CYBERSOURCE.paMerchantName") != "")
                    {
                        request.payerAuthEnrollService.merchantName = AppLogic.AppConfig("CYBERSOURCE.paMerchantName");
                    }
                    if (AppLogic.AppConfig("CYBERSOURCE.paMerchantURL") != "")
                    {
                        request.payerAuthEnrollService.merchantURL = AppLogic.AppConfig("CYBERSOURCE.paMerchantURL");
                    }
                    request.payerAuthEnrollService.httpAccept    = CommonLogic.ServerVariables("HTTP_ACCEPT");
                    request.payerAuthEnrollService.httpUserAgent = CommonLogic.ServerVariables("HTTP_USER_AGENT");
                }
                else
                {
                    request.payerAuthValidateService             = new PayerAuthValidateService();
                    request.payerAuthValidateService.signedPARes = signedPARes;
                    request.payerAuthValidateService.run         = "true";
                }
            }

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

            if (CAVV.Trim().Length != 0)
            {     // only gets set as a result of 3D Secure processing
                if (GetCardTypeFieldValue(UseBillingAddress.CardType) == "002")
                { // for MasterCard
                    request.ccAuthService.xid  = XID;
                    request.ccAuthService.cavv = CAVV;
                }
            }

            request.merchantID = AppLogic.AppConfig("CYBERSOURCE.merchantID");

            if (TransactionMode == TransactionModeEnum.authcapture)
            {
                request.ccCaptureService     = new CCCaptureService();
                request.ccCaptureService.run = "true";
            }

            BillTo billTo = new BillTo();

            billTo.firstName   = UseBillingAddress.FirstName;
            billTo.lastName    = UseBillingAddress.LastName;
            billTo.company     = UseBillingAddress.Company;
            billTo.street1     = UseBillingAddress.Address1;
            billTo.street2     = UseBillingAddress.Address2;
            billTo.city        = UseBillingAddress.City;
            billTo.state       = UseBillingAddress.State;
            billTo.postalCode  = UseBillingAddress.Zip;
            billTo.country     = AppLogic.GetCountryTwoLetterISOCode(UseBillingAddress.Country);
            billTo.phoneNumber = UseBillingAddress.Phone.PadRight(6, '1');
            billTo.email       = CommonLogic.IIF(UseBillingAddress.EMail.Length > 2, UseBillingAddress.EMail, "*****@*****.**");
            billTo.ipAddress   = CommonLogic.CustomerIpAddress();
            request.billTo     = billTo;

            if (UseShippingAddress != null)
            {
                ShipTo ShipTo = new ShipTo();
                ShipTo.firstName   = UseShippingAddress.FirstName;
                ShipTo.lastName    = UseShippingAddress.LastName;
                ShipTo.company     = UseShippingAddress.Company;
                ShipTo.street1     = UseShippingAddress.Address1;
                ShipTo.street2     = UseShippingAddress.Address2;
                ShipTo.city        = UseShippingAddress.City;
                ShipTo.state       = UseShippingAddress.State;
                ShipTo.postalCode  = UseShippingAddress.Zip;
                ShipTo.country     = AppLogic.GetCountryTwoLetterISOCode(UseShippingAddress.Country);
                ShipTo.phoneNumber = UseShippingAddress.Phone.PadRight(6, '1');
                ShipTo.email       = CommonLogic.IIF(UseShippingAddress.EMail.Length > 2, UseShippingAddress.EMail, "*****@*****.**");
                request.shipTo     = ShipTo;
            }

            Card card = new Card();

            card.accountNumber = UseBillingAddress.CardNumber;
            if (CardExtraCode.Trim().Length != 0)
            {
                card.cvIndicator = "1";
                card.cvNumber    = CardExtraCode;
            }
            else
            {
                card.cvIndicator = "0";
            }

            if (!String.IsNullOrEmpty(UseBillingAddress.CardStartDate) && UseBillingAddress.CardStartDate != "00")
            {
                card.startMonth = UseBillingAddress.CardStartDate.Substring(0, 2);
                card.startYear  = UseBillingAddress.CardStartDate.Substring(4, 2);
            }

            if (UseBillingAddress.CardIssueNumber.Length != 0)
            {
                card.issueNumber = UseBillingAddress.CardIssueNumber;
            }
            card.expirationMonth = UseBillingAddress.CardExpirationMonth;
            card.expirationYear  = UseBillingAddress.CardExpirationYear;

            if (Try3DSecure)
            {
                card.cardType = GetCardTypeFieldValue(UseBillingAddress.CardType);
                if (card.cardType == "000")
                {
                    return(" Error in configuration. Card type " + UseBillingAddress.CardType + " is not recognized by the gateway.");
                }
            }

            request.card = card;

            request.item = new Item[1];
            Item the_item = new Item();

            the_item.id        = "0";
            the_item.unitPrice = Localization.CurrencyStringForGatewayWithoutExchangeRate(OrderTotal);
            request.item[0]    = the_item;

            PurchaseTotals ptotal = new PurchaseTotals();

            ptotal.currency         = Localization.StoreCurrency();                                         // Currency REQUIRED
            ptotal.grandTotalAmount = Localization.CurrencyStringForGatewayWithoutExchangeRate(OrderTotal); // Not needed - can use instead of item price, I think it's better..
            request.purchaseTotals  = ptotal;                                                               // Neccessary

            result = "ERROR: ";


            try
            {
                ReplyMessage reply = SoapClient.RunTransaction(conf, request);

                if (Try3DSecure && request.payerAuthEnrollService != null)
                {
                    if (request.payerAuthEnrollService.run == "true")
                    { // we have some data that needs stored
                        string LookupResult = String.Empty;
                        if (reply.payerAuthEnrollReply != null &&
                            reply.payerAuthEnrollReply.paReq != null &&
                            reply.payerAuthEnrollReply.paReq.Length > 0)
                        { // will be null if card not enrolled
                            // the paReq comes back encoded, Streamline requires it to be decoded.
                            string sPAReq = CommonLogic.UnzipBase64DataToString(reply.payerAuthEnrollReply.paReq);
                            LookupResult += "paReq=" + XmlCommon.PrettyPrintXml(sPAReq) + System.Environment.NewLine;
                        }
                        if (reply.payerAuthEnrollReply != null &&
                            reply.payerAuthEnrollReply.proofXML != null)
                        {
                            /****************************************************************
                            *  Store the complete proofXML whenever it is                  *
                            *  returned. If you ever need to show proof of                 *
                            *  enrollment checking, you will need to parse the string      *
                            *  for the information required by the card association.       *
                            ****************************************************************/
                            LookupResult += "proofXML data =";
                            LookupResult += System.Environment.NewLine + XmlCommon.PrettyPrintXml(reply.payerAuthEnrollReply.proofXML);
                        }
                        if (LookupResult != String.Empty)
                        { // encode it to store in the session, it will be decoded before being saved to the database
                            byte[] str = Encoding.UTF8.GetBytes(LookupResult);
                            cSession["3DSecure.LookupResult"] = Convert.ToBase64String(str);
                        }
                    }
                }

                if (reply.decision == "REJECT" && reply.reasonCode == "475")
                { // card enrolled, must perform 3D Secure processing (reasonCode == 475)
                    cSession["3DSecure.CustomerID"]  = CustomerID.ToString();
                    cSession["3DSecure.OrderNumber"] = OrderNumber.ToString();
                    cSession["3DSecure.MD"]          = OrderNumber.ToString();
                    cSession["3DSecure.ACSUrl"]      = reply.payerAuthEnrollReply.acsURL;
                    cSession["3DSecure.paReq"]       = reply.payerAuthEnrollReply.paReq;
                    cSession["3DSecure.XID"]         = reply.payerAuthEnrollReply.xid;
                    cSession.UpdateCustomerSession(null, null);
                    result = AppLogic.ro_3DSecure; // This is what triggers the 3D Secure IFRAME to be used.
                    return(result);
                }

                if (reply.decision == "ACCEPT" || reply.decision == "REVIEW")
                {
                    result = AppLogic.ro_OK;
                    if (AppLogic.TransactionModeIsAuthCapture())
                    {
                        AVSResult            = reply.ccAuthReply.avsCode;
                        AuthorizationResult  = reply.ccCaptureReply.reasonCode;
                        AuthorizationCode    = reply.ccAuthReply.authorizationCode;
                        AuthorizationTransID = reply.requestID;
                    }
                    else
                    {
                        AVSResult            = reply.ccAuthReply.avsCode;
                        AuthorizationResult  = reply.reasonCode;
                        AuthorizationCode    = reply.ccAuthReply.authorizationCode;
                        AuthorizationTransID = reply.requestID;
                    }
                    if (signedPARes.Length > 0)
                    {
                        if (reply.payerAuthValidateReply != null)
                        {
                            if (reply.payerAuthValidateReply.ucafAuthenticationData != null)
                            { // MasterCard SecureCode
                                AuthorizationResult += System.Environment.NewLine + "CAVV: " + reply.payerAuthValidateReply.ucafAuthenticationData;
                                AuthorizationResult += System.Environment.NewLine + "ECI: " + reply.payerAuthValidateReply.ucafCollectionIndicator;
                            }
                            else
                            { // Visa VBV
                                AuthorizationResult += System.Environment.NewLine + "CAVV: " + reply.payerAuthValidateReply.cavv;
                                AuthorizationResult += System.Environment.NewLine + "ECI: " + reply.payerAuthValidateReply.eci;
                            }
                        }
                        AuthorizationResult += System.Environment.NewLine + "signedPARes: ";
                        // Streamline requires saving the decoded PARes to the database
                        string sPARes = CommonLogic.UnzipBase64DataToString(signedPARes);

                        // zap the signature since it is long and we don't need it
                        String t1  = "<Signature ";
                        String t2  = "</Signature>";
                        String sig = t1 + CommonLogic.ExtractToken(sPARes, t1, t2) + t2;
                        AuthorizationResult += System.Environment.NewLine + XmlCommon.PrettyPrintXml(sPARes.Replace(sig, ""));
                    }
                }
                else
                {
                    result = "Your transaction was NOT approved, reason code: " + reply.reasonCode + ". ";
                    if (reply.reasonCode == "476" && reply.payerAuthValidateReply != null)
                    {
                        result += reply.payerAuthValidateReply.authenticationStatusMessage
                                  + ". Please try another payment method.";
                    }

                    else
                    {
                        result += GetReasonCodeDescription(reply.reasonCode);

                        if (reply.missingField != null)
                        {
                            foreach (string fieldname in reply.missingField)
                            {
                                result += "[" + fieldname + "]";
                            }
                        }

                        if (reply.invalidField != null)
                        {
                            foreach (string fieldname in reply.invalidField)
                            {
                                result += "[" + fieldname + "]";
                            }
                        }
                    }
                }
            }
            catch (SignException se)
            {
                result += "Error calling Cybersource gateway. Please retry your order in a few minutes or select another checkout payment option. "
                          + String.Format("Failed to sign the request with error code {0} and message {1}.", DB.SQuote(se.ErrorCode.ToString()), DB.SQuote(se.Message));
            }
            catch (SoapHeaderException she)
            {
                result += String.Format("A SOAP header exception was returned with fault code {0} and message {1}.", DB.SQuote(she.Code.ToString()), DB.SQuote(she.Message));
            }
            catch (SoapBodyException sbe)
            {
                result += String.Format("A SOAP body exception was returned with fault code {0} and message {1}.", DB.SQuote(sbe.Code.ToString()), DB.SQuote(sbe.Message));
            }
            catch (WebException we)
            {
                result += String.Format("Failed to get a response with status {0} and mmessage {1}", DB.SQuote(we.Status.ToString()), DB.SQuote(we.Message));
            }
            catch (Exception ex)
            {
                // See requirements at the top of this file.
                result += "Error calling Cybersource gateway. Please retry your order in a few minutes or select another checkout payment option.";
                result += " Error message: Make sure the required components for Cybersource are installed on the server. " + ex.Message;
                result += " <> " + ex.ToString();
            }
            return(result);
        }
Ejemplo n.º 14
0
		private static void ProcessReply( ReplyMessage reply )
		{
    		string template = GetTemplate( reply.decision.ToUpper() );
			string content  = GetContent( reply );

			/*
			 * Display result of transaction.  Being a console application,
			 * this sample simply prints out some text on the screen.  Use
			 * what is appropriate for your system (e.g. ASP.NET pages).
			 */
			Console.WriteLine( template, content );
		}
Ejemplo n.º 15
0
		private static string GetContent( ReplyMessage reply )
		{
			/*
			 * This is where you retrieve the content that will be plugged
			 * into the template.
			 * 
			 * The strings returned in this sample are mostly to demonstrate
			 * how to retrieve the reply fields.  Your application should
			 * display user-friendly messages.
			 */

			int reasonCode = int.Parse( reply.reasonCode );
			switch (reasonCode)
			{
					// Success
				case 100:
					return( 
						"\nRequest ID: " + reply.requestID +
						"\nAuthorization Code: " +
							reply.ccAuthReply.authorizationCode +
						"\nCapture Request Time: " + 
							reply.ccCaptureReply.requestDateTime +
						"\nCaptured Amount: " +
							reply.ccCaptureReply.amount );

					// Missing field(s)
				case 101:
					return(
						"\nThe following required field(s) are missing: " +
						EnumerateValues( reply.missingField ) );

					// Invalid field(s)
				case 102:
					return(
						"\nThe following field(s) are invalid: " +
						EnumerateValues( reply.invalidField ) );

					// Insufficient funds
				case 204:
					return(
						"\nInsufficient funds in the account.  Please use a " +
						"different card or select another form of payment." );

				// add additional reason codes here that you need to handle
				// specifically.

				default:
					// For all other reason codes, return an empty string,
					// in which case, the template will be displayed with no
					// specific content.
					return( String.Empty );
			}	
		}
Ejemplo n.º 16
0
 /// <summary>
 /// 增加一条数据
 /// </summary>
 public void AddReplyMessage(ReplyMessage entity)
 {
     linqHelper.InsertEntity <ReplyMessage>(entity);
 }
Ejemplo n.º 17
0
 /// <summary>
 /// 更新一条数据
 /// </summary>
 public void UpdateReplyMessage(ReplyMessage entity)
 {
     linqHelper.UpdateEntity <ReplyMessage>(entity);
 }
Ejemplo n.º 18
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
                                           );
        }
    }
Ejemplo n.º 19
0
    protected void CyberSource_Customer_Profile_Fetch()
    {
        try
        {
            /// Include the following fields in the request:
            /// merchantID
            /// merchantReferenceCode
            /// recurringSubscriptionInfo_frequency —set to on-demand.
            /// paySubscriptionCreateService_paymentRequestID —include the requestID value returned from the original transaction request.
            ///
            /// See Appendix A, "API Fields," on page 34 for detailed descriptions of the request and
            /// reply fields. See Appendix B, "Examples," on page 62 for a request and reply example.

            RequestMessage request = new RequestMessage();

            request.paySubscriptionRetrieveService     = new PaySubscriptionRetrieveService();
            request.paySubscriptionRetrieveService.run = "true"; // Tokenization?

            request.merchantReferenceCode = merchantReferenceCode.Text;

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


            ReplyMessage reply    = SoapClient.RunTransaction(request);
            string       template = ghCyberSource.GetTemplate(reply.decision.ToUpper());
            string       content  = "";
            try { content = ghCyberSource.GetContent(reply); }
            catch { content = "error"; }
            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 />reasonCode: {0}", reply.paySubscriptionCreateReply.reasonCode); } catch { }
            try { lblCatch.Text += String.Format("<br />subscriptionID: {0}", reply.paySubscriptionCreateReply.subscriptionID); } catch { }
            try { lblCatch.Text += String.Format("<br />missingField: {0}", reply.missingField.Length); } catch { String.Format("<br />missingField: {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
                                           );
        }
    }
Ejemplo n.º 20
0
    protected void CyberSource_Customer_Profile_Create()
    {
        try
        {
            #region CyberSource Tokenization
            /// Here we create the Credit Card Tokenization - in CyberSource this is actually a Subscription ID
            /// We only do this for approved transactions
            /// Include the following fields in the request:
            /// merchantID
            /// merchantReferenceCode
            /// recurringSubscriptionInfo_frequency —set to on-demand.
            /// paySubscriptionCreateService_paymentRequestID —include the requestID value returned from the original transaction request.
            ///
            /// See Appendix A, "API Fields," on page 34 for detailed descriptions of the request and
            /// reply fields. See Appendix B, "Examples," on page 62 for a request and reply example.

            RequestMessage request = new RequestMessage();
            request.paySubscriptionCreateService     = new PaySubscriptionCreateService();
            request.paySubscriptionCreateService.run = "true"; // Tokenization?

            // request.merchantID = merchantID.Text; // This is not needed since it should automatically pull it from the confg [capture in DB anyways...]

            RecurringSubscriptionInfo SubscriptionInfo = new RecurringSubscriptionInfo();
            SubscriptionInfo.frequency        = "on-demand";
            request.recurringSubscriptionInfo = SubscriptionInfo;

            request.merchantReferenceCode = merchantReferenceCode.Text;
            int cbAge = 0;
            Int32.TryParse(age.Text, out cbAge);
            if (cbAge > 60)
            {
                request.paySubscriptionCreateService.paymentRequestID = paymentRequestID2.Text;
            }
            else
            {
                request.paySubscriptionCreateService.paymentRequestID = paymentRequestID.Text;
            }

            ReplyMessage reply    = SoapClient.RunTransaction(request);
            string       template = ghCyberSource.GetTemplate(reply.decision.ToUpper());
            string       content  = "";
            try { content = ghCyberSource.GetContent(reply); }
            catch { content = "error"; }
            txtTemplate.Text = template.ToString();
            txtContent.Text  = content.ToString();
            if (content.ToString() == "Approved")
            {
                txtContent.BackColor = System.Drawing.Color.Aqua;
            }
            else
            {
                txtContent.BackColor = System.Drawing.Color.Orange;
            }
            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 />reasonCode: {0}", reply.paySubscriptionCreateReply.reasonCode); } catch { }
            try { lblCatch.Text += String.Format("<br />subscriptionID: {0}", reply.paySubscriptionCreateReply.subscriptionID); } catch { }
            try { lblCatch.Text += String.Format("<br />missingField: {0}", reply.missingField.Length); } catch { String.Format("<br />missingField: {0}", "x"); }

            String sp_subscriptionid = reply.paySubscriptionCreateReply.subscriptionID;
            String sp_decision       = reply.decision.ToUpper();
            Int32  sp_callid         = -1;
            Int32  sp_donationid     = -1;
            Int32  sp_authid         = -1;
            Int32  sp_authorid       = -1;
            Int32  sp_reasoncode     = -1;
            Int32  sp_status         = -1;
            Int32  sp_actionid       = -1;

            Int32.TryParse(callid.Text, out sp_callid);
            Int32.TryParse(donationid.Text, out sp_donationid);
            Int32.TryParse(authid.Text, out sp_authid);
            Int32.TryParse(authorid.Text, out sp_authorid);
            Int32.TryParse(reply.paySubscriptionCreateReply.reasonCode, out sp_reasoncode);

            sp_actionid = 10330001; // Tokenization - Actions | Create New Token
            if (sp_decision == "ACCEPT")
            {
                sp_status = 10340001; // Tokenization - Status | Success
            }
            else if (sp_decision == "REJECT")
            {
                sp_status = 10340002; // Tokenization - Status | Failure
            }
            else
            {
                sp_status = 10340003; // Tokenization - Status | Error
            }

            #endregion CyberSource Tokenization

            #region CyberSource Tokenization - Log

            lblTokenization.Text = "Testing...";
            Int32 sp_tokenid = CyberSource_Customer_Profile_Insert(sp_subscriptionid, sp_callid, sp_donationid, sp_authid, sp_status);
            // Need to log it regardless
            // Log has the decision and reasoncode
            if (sp_tokenid != -1)
            {
                lblTokenization.Text = "Testing...";
                CyberSource_Customer_Profile_Insert_Log(sp_tokenid, sp_authorid, sp_actionid, sp_status, sp_decision, sp_reasoncode);
            }

            #endregion CyberSource Tokenization - Log
        }
        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
                                           );
        }
    }
        private WriteConcernResult ProcessReply(ConnectionId connectionId, BsonDocument getLastErrorCommand, ReplyMessage <BsonDocument> reply)
        {
            if (reply.NumberReturned == 0)
            {
                throw new MongoCommandException(connectionId, "GetLastError reply had no documents.", getLastErrorCommand);
            }
            if (reply.NumberReturned > 1)
            {
                throw new MongoCommandException(connectionId, "GetLastError reply had more than one document.", getLastErrorCommand);
            }
            if (reply.QueryFailure)
            {
                throw new MongoCommandException(connectionId, "GetLastError reply had QueryFailure flag set.", getLastErrorCommand, reply.QueryFailureDocument);
            }

            var response = reply.Documents.Single();

            var notPrimaryOrNodeIsRecoveringException = ExceptionMapper.MapNotPrimaryOrNodeIsRecovering(connectionId, response, "err");

            if (notPrimaryOrNodeIsRecoveringException != null)
            {
                throw notPrimaryOrNodeIsRecoveringException;
            }

            var writeConcernResult = new WriteConcernResult(response);

            var mappedException = ExceptionMapper.Map(connectionId, writeConcernResult);

            if (mappedException != null)
            {
                throw mappedException;
            }

            return(writeConcernResult);
        }
        private TCommandResult ProcessReply(ConnectionId connectionId, ReplyMessage <RawBsonDocument> reply)
        {
            if (reply.NumberReturned == 0)
            {
                throw new MongoCommandException(connectionId, "Command returned no documents.", _command);
            }
            if (reply.NumberReturned > 1)
            {
                throw new MongoCommandException(connectionId, "Command returned multiple documents.", _command);
            }
            if (reply.QueryFailure)
            {
                var failureDocument = reply.QueryFailureDocument;
                throw ExceptionMapper.Map(connectionId, failureDocument) ?? new MongoCommandException(connectionId, "Command failed.", _command, failureDocument);
            }

            using (var rawDocument = reply.Documents[0])
            {
                if (!rawDocument.GetValue("ok", false).ToBoolean())
                {
                    var materializedDocument = new BsonDocument(rawDocument);
                    var commandName          = _command.GetElement(0).Name;
                    if (commandName == "$query")
                    {
                        commandName = _command["$query"].AsBsonDocument.GetElement(0).Name;
                    }

                    var notPrimaryOrNodeIsRecoveringException = ExceptionMapper.MapNotPrimaryOrNodeIsRecovering(connectionId, materializedDocument, "errmsg");
                    if (notPrimaryOrNodeIsRecoveringException != null)
                    {
                        throw notPrimaryOrNodeIsRecoveringException;
                    }

                    string    message;
                    BsonValue errmsgBsonValue;
                    if (materializedDocument.TryGetValue("errmsg", out errmsgBsonValue) && errmsgBsonValue.IsString)
                    {
                        var errmsg = errmsgBsonValue.ToString();
                        message = string.Format("Command {0} failed: {1}.", commandName, errmsg);
                    }
                    else
                    {
                        message = string.Format("Command {0} failed.", commandName);
                    }

                    var mappedException = ExceptionMapper.Map(connectionId, materializedDocument);
                    if (mappedException != null)
                    {
                        throw mappedException;
                    }

                    throw new MongoCommandException(connectionId, message, _command, materializedDocument);
                }

                using (var stream = new ByteBufferStream(rawDocument.Slice, ownsBuffer: false))
                {
                    var encoderFactory = new BinaryMessageEncoderFactory(stream, _messageEncoderSettings);
                    var encoder        = (ReplyMessageBinaryEncoder <TCommandResult>)encoderFactory.GetReplyMessageEncoder <TCommandResult>(_resultSerializer);
                    using (var reader = encoder.CreateBinaryReader())
                    {
                        var context = BsonDeserializationContext.CreateRoot(reader);
                        return(_resultSerializer.Deserialize(context));
                    }
                }
            }
        }
Ejemplo n.º 23
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);
        }
    }
Ejemplo n.º 24
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();
        }
    }
Ejemplo n.º 25
0
        // if RefundAmount == 0.0M, then then ENTIRE order amount will be refunded!
        public override String RefundOrder(int OriginalOrderNumber, int NewOrderNumber, decimal RefundAmount, String RefundReason, AspDotNetStorefrontCore.Address UseBillingAddress)
        {
            String result = AppLogic.ro_OK;

            DB.ExecuteSQL("update orders set RefundTXCommand=NULL, RefundTXResult=NULL where OrderNumber=" + OriginalOrderNumber.ToString());
            String  TransID     = String.Empty;
            int     CustomerID  = 0;
            decimal TotalAmount = 0;

            using (SqlConnection con = new SqlConnection(DB.GetDBConn()))
            {
                con.Open();
                using (IDataReader rs = DB.GetRS("select AuthorizationPNREF,OrderTotal,CustomerID from orders   with (NOLOCK)  where OrderNumber=" + OriginalOrderNumber.ToString(), con))
                {
                    if (rs.Read())
                    {
                        TransID     = DB.RSField(rs, "AuthorizationPNREF");
                        TotalAmount = DB.RSFieldDecimal(rs, "OrderTotal");
                        CustomerID  = DB.RSFieldInt(rs, "CustomerID");
                    }
                }
            }

            Configuration conf = new Configuration();

            conf.KeysDirectory = AppLogic.AppConfig("CYBERSOURCE.keysDirectory");
            conf.KeyFilename   = AppLogic.AppConfig("CYBERSOURCE.keyFilename");
            conf.MerchantID    = AppLogic.AppConfig("CYBERSOURCE.merchantID");
            conf.ServerURL     = CommonLogic.IIF(AppLogic.AppConfigBool("UseLiveTransactions"), AppLogic.AppConfig("CYBERSOURCE.LiveURL"), AppLogic.AppConfig("CYBERSOURCE.TestURL"));
            if (AppLogic.AppConfigBool("CYBERSOURCE.UsePIT"))
            {
                conf.ServerURL = AppLogic.AppConfig("CYBERSOURCE.PITURL");
            }

            RequestMessage request = new RequestMessage();

            request.clientApplication        = "AspDotNetStorefront";
            request.clientApplicationVersion = AppLogic.AppConfig("StoreVersion");
            request.clientApplicationUser    = CustomerID.ToString();

            request.merchantReferenceCode = "Order #: " + OriginalOrderNumber.ToString() + " " + Localization.ToNativeDateTimeString(System.DateTime.Now);

            request.merchantID = AppLogic.AppConfig("CYBERSOURCE.merchantID");

            request.ccCreditService = new CCCreditService();
            request.ccCreditService.captureRequestID = TransID;
            request.ccCreditService.run = "true";

            if (RefundAmount == System.Decimal.Zero)
            {
                RefundAmount = TotalAmount;
            }

            PurchaseTotals ptotal = new PurchaseTotals();

            ptotal.currency         = Localization.StoreCurrency(); // Currency REQUIRED
            ptotal.grandTotalAmount = Localization.CurrencyStringForGatewayWithoutExchangeRate(CommonLogic.IIF(RefundAmount > TotalAmount, TotalAmount, RefundAmount));
            request.purchaseTotals  = ptotal;                       // Neccessary

            result = "ERROR: ";

            try
            {
                ReplyMessage reply = SoapClient.RunTransaction(conf, request);
                if (reply.ccCreditReply.reasonCode == "100")
                {
                    result = AppLogic.ro_OK;
                }
                else
                {
                    result += GetReasonCodeDescription(reply.reasonCode);
                }
            }
            catch (SignException se)
            {
                result += String.Format("Failed to sign the request with error code {0} and message {1}.", DB.SQuote(se.ErrorCode.ToString()), DB.SQuote(se.Message));
            }
            catch (SoapHeaderException she)
            {
                result += String.Format("A SOAP header exception was returned with fault code {0} and message {1}.", DB.SQuote(she.Code.ToString()), DB.SQuote(she.Message));
            }
            catch (SoapBodyException sbe)
            {
                result += String.Format("A SOAP body exception was returned with fault code {0} and message {1}.", DB.SQuote(sbe.Code.ToString()), DB.SQuote(sbe.Message));
            }
            catch (WebException we)
            {
                result += String.Format("Failed to get a response with status {0} and message {1}", DB.SQuote(we.Status.ToString()), DB.SQuote(we.Message));
            }
            catch (Exception ex)
            {
                result += ex.Message;
            }
            DB.ExecuteSQL("update orders set RefundTXResult=" + DB.SQuote(result) + " where OrderNumber=" + OriginalOrderNumber.ToString());

            return(result);
        }
 public void Send(ReplyMessage message)
 {
     _messages.Add(message);
     _replyMessages.Add(message);
 }
Ejemplo n.º 27
0
        public override String CaptureOrder(Order o)
        {
            String result = AppLogic.ro_OK;

            o.CaptureTXCommand = "";
            o.CaptureTXResult  = "";
            String  TransID     = o.AuthorizationPNREF;
            Decimal TotalAmount = o.OrderBalance;
            int     CustomerID  = o.CustomerID;

            Configuration conf = new Configuration();

            conf.KeysDirectory = AppLogic.AppConfig("CYBERSOURCE.keysDirectory");
            conf.KeyFilename   = AppLogic.AppConfig("CYBERSOURCE.keyFilename");
            conf.MerchantID    = AppLogic.AppConfig("CYBERSOURCE.merchantID");
            conf.ServerURL     = CommonLogic.IIF(AppLogic.AppConfigBool("UseLiveTransactions"), AppLogic.AppConfig("CYBERSOURCE.LiveURL"), AppLogic.AppConfig("CYBERSOURCE.TestURL"));
            if (AppLogic.AppConfigBool("CYBERSOURCE.UsePIT"))
            {
                conf.ServerURL = AppLogic.AppConfig("CYBERSOURCE.PITURL");
            }

            RequestMessage request = new RequestMessage();

            request.clientApplication        = "AspDotNetStorefront";
            request.clientApplicationVersion = AppLogic.AppConfig("StoreVersion");
            request.clientApplicationUser    = CustomerID.ToString();

            request.merchantReferenceCode = "Order #: " + o.OrderNumber.ToString() + " " + Localization.ToNativeDateTimeString(System.DateTime.Now);

            request.merchantID = AppLogic.AppConfig("CYBERSOURCE.merchantID");

            request.ccCaptureService = new CCCaptureService();
            request.ccCaptureService.authRequestID = TransID;
            request.ccCaptureService.run           = "true";

            PurchaseTotals ptotal = new PurchaseTotals();

            ptotal.currency         = Localization.StoreCurrency(); // Currency REQUIRED
            ptotal.grandTotalAmount = Localization.CurrencyStringForGatewayWithoutExchangeRate(TotalAmount);
            request.purchaseTotals  = ptotal;                       // Neccessary
            result = "ERROR: ";

            try
            {
                ReplyMessage reply = SoapClient.RunTransaction(conf, request);
                if (reply.ccCaptureReply.reasonCode == "100")
                {
                    result = AppLogic.ro_OK;
                }
                else
                {
                    result += GetReasonCodeDescription(reply.reasonCode);
                }
            }
            catch (SignException se)
            {
                result += String.Format("Failed to sign the request with error code {0} and message {1}.", DB.SQuote(se.ErrorCode.ToString()), DB.SQuote(se.Message));
            }
            catch (SoapHeaderException she)
            {
                result += String.Format("A SOAP header exception was returned with fault code {0} and message {1}.", DB.SQuote(she.Code.ToString()), DB.SQuote(she.Message));
            }
            catch (SoapBodyException sbe)
            {
                result += String.Format("A SOAP body exception was returned with fault code {0} and message {1}.", DB.SQuote(sbe.Code.ToString()), DB.SQuote(sbe.Message));
            }
            catch (WebException we)
            {
                result += String.Format("Failed to get a response with status {0} and message {1}", DB.SQuote(we.Status.ToString()), DB.SQuote(we.Message));
            }
            catch (Exception ex)
            {
                result += ex.Message;
            }
            o.CaptureTXResult = result;

            return(result);
        }
Ejemplo n.º 28
0
        private void ProcessGLEReplyMessage(CommandState state, ReplyMessage <RawBsonDocument> replyMessage, ConnectionId connectionId)
        {
            var       reply = replyMessage.Documents[0];
            BsonValue ok;

            if (!reply.TryGetValue("ok", out ok))
            {
                // this is a degenerate case with the server and
                // we don't really know what to do here...
            }
            else if (!ok.ToBoolean())
            {
                if (_failedEvent != null)
                {
                    _failedEvent(new CommandFailedEvent(
                                     state.CommandName,
                                     new MongoCommandException(
                                         connectionId,
                                         string.Format("{0} command failed", state.CommandName),
                                         null,
                                         reply),
                                     state.OperationId,
                                     replyMessage.ResponseTo,
                                     connectionId,
                                     state.Stopwatch.Elapsed));
                }
            }
            else if (_succeededEvent != null)
            {
                var fakeReply = new BsonDocument("ok", 1);

                BsonValue n;
                if (reply.TryGetValue("n", out n))
                {
                    fakeReply["n"] = n;
                }

                BsonValue err;
                if (reply.TryGetValue("err", out err) && err != BsonNull.Value)
                {
                    var code   = reply.GetValue("code", -1);
                    var errmsg = err.ToString();
                    var isWriteConcernError = __writeConcernIndicators.Any(x => errmsg.Contains(x));
                    if (isWriteConcernError)
                    {
                        fakeReply["writeConcernError"] = new BsonDocument
                        {
                            { "code", code },
                            { "errmsg", err }
                        };
                    }
                    else
                    {
                        fakeReply["writeErrors"] = new BsonArray(new[] { new BsonDocument
                                                                         {
                                                                             { "index", 0 },
                                                                             { "code", code },
                                                                             { "errmsg", err }
                                                                         } });
                    }
                }
                else if (state.CommandName == "insert")
                {
                    fakeReply["n"] = state.NumberOfInsertedDocuments;
                }
                else if (state.CommandName == "update")
                {
                    // Unfortunately v2.4 GLE does not include the upserted field when
                    // the upserted _id is non-OID type.  We can detect this by the
                    // updatedExisting field + an n of 1
                    BsonValue upsertedValue;
                    var       upserted = reply.TryGetValue("upserted", out upsertedValue) ||
                                         (n == 1 && !reply.GetValue("updatedExisting", false).ToBoolean());

                    if (upserted)
                    {
                        fakeReply["upserted"] = new BsonArray(new[] { new BsonDocument
                                                                      {
                                                                          { "index", 0 },
                                                                          { "_id", upsertedValue ?? state.UpsertedId ?? BsonUndefined.Value }
                                                                      } });
                    }
                }

                _succeededEvent(new CommandSucceededEvent(
                                    state.CommandName,
                                    fakeReply,
                                    state.OperationId,
                                    replyMessage.ResponseTo,
                                    connectionId,
                                    state.Stopwatch.Elapsed));
            }
        }
Ejemplo n.º 29
0
        public List <ReplyMessage> bubble()
        {
            var lrm = new List <ReplyMessage>();

            // foreach (var lc in llc)
            {
                var rm = new ReplyMessage();
                rm.type    = "flex";
                rm.altText = "test";
                //rm.styles = new Styles()
                //{
                //    header = new Header() { backgroundColor = "#ffaaaa" },
                //    body = new Body() { backgroundColor = "#aaffaa" },
                //    footer = new Footer() { backgroundColor = "#aaaaff" },
                //};
                rm.header = new Header2
                {
                    type     = "box",
                    layout   = "vertical",
                    contents = new List <Content>()
                    {
                        new Content()
                        {
                            type = "text", text = "header"
                        }
                    }
                };
                rm.hero = new Hero()
                {
                    type = "image",
                    //aspectRatio = "2:1",
                    //size = "full",
                    url = "https://i.imgur.com/wEl3Uvz.png"
                };
                rm.body = new Body2()
                {
                    type     = "box",
                    layout   = "vertical",
                    contents = new List <Content2>()
                    {
                        new Content2()
                        {
                            type = "text", text = "body"
                        }
                    }
                };
                rm.footer = new Footer2()
                {
                    type     = "box",
                    layout   = "vertical",
                    contents = new List <Content3>()
                    {
                        new Content3()
                        {
                            type = "text", text = "footer"
                        }
                    }
                };


                lrm.Add(rm);
            }
            return(lrm);
        }
        /// <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
                    proc.ClientCredentials.ClientCertificate.Certificate = GetCertificate(config);

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

                    // Changes for SHA2 certificates support
                    X509Certificate2Collection collection = GetCertificateCollection(config);

                    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();
                }
            }
        }
Ejemplo n.º 31
0
        public WorkItem Pull(ReplyMessage reply)
        {
            if (reply == null) throw new ArgumentNullException("reply");

            reply.Direction = MessageDirection.Incoming;

            Logger.Trace(String.Format("Incoming Reply '{0}' for Event '{1}' has been queued."
                , reply.CorrelationId
                , reply.Event)
                /*, new XmlLogAttachment("Request", request)*/);

            Action sinkChainInvocation = () => Sinks.InvokeTransactional(reply);
            WorkItem workItem = new WorkItem(reply, sinkChainInvocation);

            workItem.Completed += delegate(object sender, EventArgs e)
            {
                Logger.Trace(String.Format("Incoming Reply '{0}' for Event '{1}' was successfully processed."
                    , reply.CorrelationId
                    , reply.Event)
                    /*, new XmlLogAttachment("Reply", reply)*/);
            };

            workItem.Error += delegate(object sender, ItemEventArgs<Exception> e)
            {
                Exception exception = e.Item;
                Logger.Error(String.Format("Error occurred while processing Incoming Reply '{0}' for Event '{1}'."
                    , reply.CorrelationId
                    , reply.Event)
                    , exception
                    /*, new XmlLogAttachment("Reply", reply)*/);
            };

            Queue.QueueWorkItem(workItem);
            return workItem;
        }
Ejemplo n.º 32
0
        public void GetEncoder_should_return_encoder()
        {
            var subject = new ReplyMessage<BsonDocument>(true, _cursorId, false, _documents, _numberReturned, false, null, _requestId, _responseTo, _serializer, _startingFrom);
            var mockEncoderFactory = new Mock<IMessageEncoderFactory>();
            var encoder = new Mock<IMessageEncoder>().Object;
            mockEncoderFactory.Setup(f => f.GetReplyMessageEncoder(_serializer)).Returns(encoder);

            var result = subject.GetEncoder(mockEncoderFactory.Object);

            result.Should().BeSameAs(encoder);
        }
        public void WriteMessage_should_encode_flags_correctly(int flags, bool cursorNotFound, bool queryFailure, bool awaitCapable)
        {
            var documents = queryFailure ? null : __documents;
            var queryFailureDocument = queryFailure ? new BsonDocument("ok", 0) : null;
            var message = new ReplyMessage<BsonDocument>(awaitCapable, __cursorId, cursorNotFound, documents, __numberReturned, queryFailure, queryFailureDocument, __requestId, __responseTo, __serializer, __startingFrom);

            using (var stream = new MemoryStream())
            {
                var subject = new ReplyMessageBinaryEncoder<BsonDocument>(stream, __messageEncoderSettings, __serializer);
                subject.WriteMessage(message);
                var bytes = stream.ToArray();
                bytes[__flagsOffset].Should().Be((byte)flags);
            }
        }
        private void ProcessCommandReplyMessage(CommandState state, ReplyMessage<RawBsonDocument> replyMessage, ConnectionId connectionId)
        {
            BsonDocument reply = replyMessage.Documents[0];
            BsonValue ok;
            if (!reply.TryGetValue("ok", out ok))
            {
                // this is a degenerate case with the server and 
                // we don't really know what to do here...
                return;
            }

            if (__securitySensitiveCommands.Contains(state.CommandName))
            {
                reply = new BsonDocument();
            }

            if (!ok.ToBoolean())
            {
                if (_failedEvent != null)
                {
                    _failedEvent(new CommandFailedEvent(
                        state.CommandName,
                        new MongoCommandException(
                            connectionId,
                            string.Format("{0} command failed", state.CommandName),
                            null,
                            reply),
                        state.OperationId,
                        replyMessage.ResponseTo,
                        connectionId,
                        state.Stopwatch.Elapsed));
                }
            }
            else if (_succeededEvent != null)
            {
                _succeededEvent(new CommandSucceededEvent(
                    state.CommandName,
                    reply,
                    state.OperationId,
                    replyMessage.ResponseTo,
                    connectionId,
                    state.Stopwatch.Elapsed));
            }
        }
Ejemplo n.º 35
0
        /// <summary>
        /// Processes the error message.
        /// </summary>
        /// <param name="reply">The reply.</param>
        /// <returns></returns>
        private string ProcessError( ReplyMessage reply )
        {
            // Make sure the reply is valid
            if ( reply == null )
            {
                return "Invalid response from the paymnent gateway.";
            }

            int reasonCode = int.Parse( reply.reasonCode );
            switch ( reasonCode )
            {
                // Missing field or fields
                case 101:
                    return "\nThe following required fields are missing: " + string.Join( "\n", reply.missingField ?? new string[0] );
                // Invalid field or fields
                case 102:
                    return "\nThe following fields are invalid: " + string.Join( "\n", reply.invalidField ?? new string[0] );
                // Partial payment approved
                case 110:
                    return "\nOnly a partial amount of this transaction was approved.";
                // General system failure
                case 150:
                    return string.Format( "\nThe payment processor did not process your payment. {0}", reply.additionalData );
                // System timeout
                case 151:
                    return string.Format( "\nThe payment request timed out. {0}", reply.additionalData ); ;
                // Service request timed out
                case 152:
                    return "\nThe payment service timed out.";
                // AVS check failed
                case 200:
                    return "\nThe payment billing address did not match the bank's address on record. Please verify your address details.";
                // Expired card
                case 202:
                    return "\nThe card has expired. Please use a different card or select another form of payment.";
                // Card declined
                case 203:
                    return "\nThe card was declined without a reason given. Please use a different card or select another form of payment.";
                // Insufficient funds
                case 204:
                    return "\nInsufficient funds in the account. Please use another form of payment.";
                // Stolen card
                case 205:
                    return "\nThe card has been reported stolen. Please use a different card or select another form of payment.";
                // Bank unavailable
                case 207:
                    return "\nThe bank processor is temporarily unavailable. Please try again in a few minutes.";
                // Card not active
                case 208:
                    return "\nThe card is inactive or not authorized for internet transactions. Please use a different card or select another form of payment.";
                // AmEx invalid CID
                case 209:
                    return "\nThe card identification digit did not match.  Please use a different card or select another form of payment.";
                // Maxed out
                case 210:
                    return "\nThe card has reached its credit limit.  Please use a different card or select another form of payment.";
                // Invalid verification #
                case 211:
                    return "\nThe card verification number is invalid. Please verify your 3 or 4 digit verification number.";
                // Frozen account
                case 222:
                    return "\nThe selected account has been frozen. Please use another form of payment.";
                // Invalid verification #
                case 230:
                    return "\nThe card verification number is invalid. Please verify your 3 or 4 digit verification number.";
                // Invalid account #
                case 231:
                    return "\nThe account number is invalid. Please use another form of payment.";
                // Invalid merchant config
                case 234:
                    return "\nThe merchant configuration is invalid. Please contact CyberSource customer support.";
                // Processor failure
                case 236:
                    return "\nThe payment processor is offline. Please try again in a few minutes.";
                // Card type not accepted
                case 240:
                    return "\nThe card type is not accepted by the merchant. Please use another form of payment.";
                // Payment processor timeout
                case 250:
                    return "\nThe payment request was received but has not yet been processed.";
                // Any others not identified
                default:
                    return string.Format( "\nYour payment was not processed. {0}", reply.additionalData );
            }
        }
        private void ProcessQueryReplyMessage(CommandState state, ReplyMessage<RawBsonDocument> replyMessage, ConnectionId connectionId)
        {
            if (_succeededEvent != null)
            {
                BsonDocument reply;
                if (state.CommandName == "explain")
                {
                    reply = new BsonDocument("ok", 1);
                    reply.Merge(replyMessage.Documents[0]);
                }
                else
                {
                    var batchName = state.CommandName == "find" ? "firstBatch" : "nextBatch";
                    reply = new BsonDocument
                    {
                        { "cursor", new BsonDocument
                                    {
                                        { "id", replyMessage.CursorId },
                                        { "ns", state.QueryNamespace.FullName },
                                        { batchName, new BsonArray(replyMessage.Documents) }
                                    }},
                        { "ok", 1 }
                    };
                }

                _succeededEvent(new CommandSucceededEvent(
                    state.CommandName,
                    reply,
                    state.OperationId,
                    replyMessage.ResponseTo,
                    connectionId,
                    state.Stopwatch.Elapsed));
            }
        }
Ejemplo n.º 37
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);
    }
Ejemplo n.º 38
0
 public outputMessageOut(ReplyMessage replyMessage)
 {
     this.replyMessage = replyMessage;
 }
        public void GetEncoder_should_return_encoder()
        {
            var subject = new ReplyMessage<BsonDocument>(true, _cursorId, false, _documents, _numberReturned, false, null, _requestId, _responseTo, _serializer, _startingFrom);
            var stubEncoderFactory = Substitute.For<IMessageEncoderFactory>();
            var stubEncoder = Substitute.For<IMessageEncoder>();
            stubEncoderFactory.GetReplyMessageEncoder(_serializer).Returns(stubEncoder);

            var result = subject.GetEncoder(stubEncoderFactory);

            result.Should().BeSameAs(stubEncoder);
        }
Ejemplo n.º 40
0
 public void EnqueueReplyMessage <TDocument>(ReplyMessage <TDocument> replyMessage)
 {
     _replyMessages.Enqueue(replyMessage);
 }
Ejemplo n.º 41
0
        /// <summary>
        /// Sends a reply message in response to an event from a user, group, or room.
        /// </summary>
        /// <param name="replyMessage">Reply message.</param>
        /// <returns>Messaging API response.</returns>
        /// <remarks>
        /// To send reply messages, you must have a reply token which is included in a webhook event object.<br/><br/>
        /// <a href="https://developers.line.biz/en/reference/messaging-api/#webhooks">Webhooks</a> are used to notify you when an event occurs.For events that you can respond to, a reply token is issued for replying to messages.<br/><br/>
        /// Because the reply token becomes invalid after a certain period of time, responses should be sent as soon as a message is received.Reply tokens can only be used once.<br/><br/>
        /// See <a href="https://developers.line.biz/en/reference/messaging-api/#send-reply-message">Here</a>.
        /// </remarks>
        public async Task <MessagingApiResponse> SendReplyMessageAsync(ReplyMessage replyMessage)
        {
            var json = JsonConvert.SerializeObject(replyMessage, _settings);

            return(await SendReplyMessageAsync(json));
        }
Ejemplo n.º 42
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();
        }
        private void ProcessGLEReplyMessage(CommandState state, ReplyMessage<RawBsonDocument> replyMessage, ConnectionId connectionId)
        {
            var reply = replyMessage.Documents[0];
            BsonValue ok;
            if (!reply.TryGetValue("ok", out ok))
            {
                // this is a degenerate case with the server and 
                // we don't really know what to do here...
            }
            else if (!ok.ToBoolean())
            {
                if (_failedEvent != null)
                {
                    _failedEvent(new CommandFailedEvent(
                        state.CommandName,
                        new MongoCommandException(
                            connectionId,
                            string.Format("{0} command failed", state.CommandName),
                            null,
                            reply),
                        state.OperationId,
                        replyMessage.ResponseTo,
                        connectionId,
                        state.Stopwatch.Elapsed));
                }
            }
            else if (_succeededEvent != null)
            {
                var fakeReply = new BsonDocument("ok", 1);

                BsonValue n;
                if (reply.TryGetValue("n", out n))
                {
                    fakeReply["n"] = n;
                }

                BsonValue err;
                if (reply.TryGetValue("err", out err) && err != BsonNull.Value)
                {
                    var code = reply.GetValue("code", -1);
                    var errmsg = err.ToString();
                    var isWriteConcernError = __writeConcernIndicators.Any(x => errmsg.Contains(x));
                    if (isWriteConcernError)
                    {
                        fakeReply["writeConcernError"] = new BsonDocument
                        {
                            { "code", code },
                            { "errmsg", err }
                        };
                    }
                    else
                    {
                        fakeReply["writeErrors"] = new BsonArray(new[] { new BsonDocument
                        {
                            { "index", 0 },
                            { "code", code },
                            { "errmsg", err }
                        }});
                    }
                }
                else if (state.CommandName == "insert")
                {
                    fakeReply["n"] = state.NumberOfInsertedDocuments;
                }
                else if (state.CommandName == "update")
                {
                    // Unfortunately v2.4 GLE does not include the upserted field when
                    // the upserted _id is non-OID type.  We can detect this by the
                    // updatedExisting field + an n of 1
                    BsonValue upsertedValue;
                    var upserted = reply.TryGetValue("upserted", out upsertedValue) ||
                        (n == 1 && !reply.GetValue("updatedExisting", false).ToBoolean());

                    if (upserted)
                    {
                        fakeReply["upserted"] = new BsonArray(new[] { new BsonDocument
                        {
                            { "index", 0 },
                            { "_id", upsertedValue ?? state.UpsertedId ?? BsonUndefined.Value }
                        }});
                    }
                }

                _succeededEvent(new CommandSucceededEvent(
                    state.CommandName,
                    fakeReply,
                    state.OperationId,
                    replyMessage.ResponseTo,
                    connectionId,
                    state.Stopwatch.Elapsed));
            }
        }
        private TCommandResult ProcessReply(ConnectionId connectionId, ReplyMessage <RawBsonDocument> reply)
        {
            if (reply.NumberReturned == 0)
            {
                throw new MongoCommandException(connectionId, "Command returned no documents.", _command);
            }
            if (reply.NumberReturned > 1)
            {
                throw new MongoCommandException(connectionId, "Command returned multiple documents.", _command);
            }
            if (reply.QueryFailure)
            {
                var failureDocument = reply.QueryFailureDocument;
                throw ExceptionMapper.Map(connectionId, failureDocument) ?? new MongoCommandException(connectionId, "Command failed.", _command, failureDocument);
            }

            using (var rawDocument = reply.Documents[0])
            {
                var binaryReaderSettings = new BsonBinaryReaderSettings();
                if (_messageEncoderSettings != null)
                {
                    binaryReaderSettings.Encoding = _messageEncoderSettings.GetOrDefault <UTF8Encoding>(MessageEncoderSettingsName.ReadEncoding, Utf8Encodings.Strict);
#pragma warning disable 618
                    if (BsonDefaults.GuidRepresentationMode == GuidRepresentationMode.V2)
                    {
                        binaryReaderSettings.GuidRepresentation = _messageEncoderSettings.GetOrDefault <GuidRepresentation>(MessageEncoderSettingsName.GuidRepresentation, GuidRepresentation.CSharpLegacy);
                    }
#pragma warning restore 618
                }
                ;

                BsonValue clusterTime;
                if (rawDocument.TryGetValue("$clusterTime", out clusterTime))
                {
                    // note: we are assuming that _session is an instance of ClusterClockAdvancingClusterTime
                    // and that calling _session.AdvanceClusterTime will have the side effect of advancing the cluster's ClusterTime also
                    var materializedClusterTime = ((RawBsonDocument)clusterTime).Materialize(binaryReaderSettings);
                    _session.AdvanceClusterTime(materializedClusterTime);
                }
                BsonValue operationTime;
                if (rawDocument.TryGetValue("operationTime", out operationTime))
                {
                    _session.AdvanceOperationTime(operationTime.AsBsonTimestamp);
                }

                if (!rawDocument.GetValue("ok", false).ToBoolean())
                {
                    var materializedDocument = rawDocument.Materialize(binaryReaderSettings);

                    var commandName = _command.GetElement(0).Name;
                    if (commandName == "$query")
                    {
                        commandName = _command["$query"].AsBsonDocument.GetElement(0).Name;
                    }

                    var notPrimaryOrNodeIsRecoveringException = ExceptionMapper.MapNotPrimaryOrNodeIsRecovering(connectionId, _command, materializedDocument, "errmsg");
                    if (notPrimaryOrNodeIsRecoveringException != null)
                    {
                        throw notPrimaryOrNodeIsRecoveringException;
                    }

                    string    message;
                    BsonValue errmsgBsonValue;
                    if (materializedDocument.TryGetValue("errmsg", out errmsgBsonValue) && errmsgBsonValue.IsString)
                    {
                        var errmsg = errmsgBsonValue.ToString();
                        message = string.Format("Command {0} failed: {1}.", commandName, errmsg);
                    }
                    else
                    {
                        message = string.Format("Command {0} failed.", commandName);
                    }

                    var mappedException = ExceptionMapper.Map(connectionId, materializedDocument);
                    if (mappedException != null)
                    {
                        throw mappedException;
                    }

                    throw new MongoCommandException(connectionId, message, _command, materializedDocument);
                }

                if (rawDocument.Contains("writeConcernError"))
                {
                    var materializedDocument = rawDocument.Materialize(binaryReaderSettings);
                    var writeConcernError    = materializedDocument["writeConcernError"].AsBsonDocument;
                    var message            = writeConcernError.AsBsonDocument.GetValue("errmsg", null)?.AsString;
                    var writeConcernResult = new WriteConcernResult(materializedDocument);
                    throw new MongoWriteConcernException(connectionId, message, writeConcernResult);
                }

                using (var stream = new ByteBufferStream(rawDocument.Slice, ownsBuffer: false))
                {
                    var encoderFactory = new BinaryMessageEncoderFactory(stream, _messageEncoderSettings);
                    var encoder        = (ReplyMessageBinaryEncoder <TCommandResult>)encoderFactory.GetReplyMessageEncoder <TCommandResult>(_resultSerializer);
                    using (var reader = encoder.CreateBinaryReader())
                    {
                        var context = BsonDeserializationContext.CreateRoot(reader);
                        return(_resultSerializer.Deserialize(context));
                    }
                }
            }
        }
        //For Cybersource: save merchant reference code, request id, and merchant id into a lookup table for void functionality. djk 3.21.14
        public void SaveCyberSourceResponse(PurchaseOrder order, ReplyMessage response, string siteName)
        {
            var sb = new StringBuilder();

            try
            {
                var requestId = "";
                var merchantId = "";
                var merchantReferenceCode = "";
                var _siteName = siteName;

                sb.Append("Entering save reponse\r\n");

                //call to get correct merchant id based on site name
                if (!String.IsNullOrEmpty(_siteName))
                {
                    merchantId = Util.ConvertSiteNameToMerchantId(_siteName);
                }

                //merchant reference code
                if (!string.IsNullOrEmpty(order.PO))
                {
                    merchantReferenceCode = order.PO;
                }

                sb.Append("Save response site name: " + _siteName + "\r\n");
                sb.Append("Save response merchant ID = " + merchantId + "\r\n");

                //request id
                if (!string.IsNullOrEmpty(response.requestID))
                {
                    requestId = response.requestID;
                }

                if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["CyberSourceTransactionsConnectionString"]))
                {
                    var connectionString = ConfigurationManager.AppSettings["CyberSourceTransactionsConnectionString"];
                    var insertCybersourceResponse = "InsertCyberSourceResponse";

                    sb.Append("connection string: " + connectionString + "\r\n");

                    using (SqlConnection conn = new SqlConnection(connectionString))
                    {
                        conn.Open();

                        sb.Append("connection string open \r\n");

                        SqlParameter requestIdParam = new SqlParameter
                        {
                            ParameterName = "RequestId",
                            SqlDbType = SqlDbType.VarChar,
                            Direction = ParameterDirection.Input,
                            Value = requestId

                        };

                        SqlParameter merchantIdParam = new SqlParameter()
                        {
                            ParameterName = "MerchantId",
                            SqlDbType = SqlDbType.VarChar,
                            Direction = ParameterDirection.Input,
                            Value = merchantId
                        };

                        SqlParameter merchantReferenceCodeParam = new SqlParameter()
                        {
                            ParameterName =
                                "MerchantReferenceCode",
                            SqlDbType = SqlDbType.VarChar,
                            Direction = ParameterDirection.Input,
                            Value = merchantReferenceCode
                        };


                        if (conn != null)
                        {
                            SqlCommand command = new SqlCommand(insertCybersourceResponse, conn);
                            command.CommandType = CommandType.StoredProcedure;
                            command.Parameters.Add(requestIdParam);
                            command.Parameters.Add(merchantIdParam);
                            command.Parameters.Add(merchantReferenceCodeParam);

                            var result = command.ExecuteNonQuery();
                        }
                    }
                }
                else
                {
                    sb.Append("save response connection string from config is empty.");
                }

                TraceToLogSaveResponse(sb.ToString());
            }
            catch (ApplicationException e)
            {
                sb.Append("Error: " + e.Message);
                TraceToLogSaveResponse(sb.ToString());
                throw new Exception(e.Message);
            }
        }
Ejemplo n.º 46
0
        public override String VoidOrder(int OrderNumber)
        {
            String result = AppLogic.ro_OK;

            DB.ExecuteSQL("update orders set VoidTXCommand=NULL, VoidTXResult=NULL where OrderNumber=" + OrderNumber.ToString());
            String TransID    = String.Empty;
            int    CustomerID = 0;

            using (SqlConnection con = new SqlConnection(DB.GetDBConn()))
            {
                con.Open();
                using (IDataReader rs = DB.GetRS("select AuthorizationPNREF,CustomerID from orders   with (NOLOCK)  where OrderNumber=" + OrderNumber.ToString(), con))
                {
                    if (rs.Read())
                    {
                        TransID    = DB.RSField(rs, "AuthorizationPNREF");
                        CustomerID = DB.RSFieldInt(rs, "CustomerID");
                    }
                }
            }

            Configuration conf = new Configuration();

            conf.KeysDirectory = AppLogic.AppConfig("CYBERSOURCE.keysDirectory");
            conf.KeyFilename   = AppLogic.AppConfig("CYBERSOURCE.keyFilename");
            conf.MerchantID    = AppLogic.AppConfig("CYBERSOURCE.merchantID");
            conf.ServerURL     = CommonLogic.IIF(AppLogic.AppConfigBool("UseLiveTransactions"), AppLogic.AppConfig("CYBERSOURCE.LiveURL"), AppLogic.AppConfig("CYBERSOURCE.TestURL"));
            if (AppLogic.AppConfigBool("CYBERSOURCE.UsePIT"))
            {
                conf.ServerURL = AppLogic.AppConfig("CYBERSOURCE.PITURL");
            }

            RequestMessage request = new RequestMessage();

            request.clientApplication        = "AspDotNetStorefront";
            request.clientApplicationVersion = AppLogic.AppConfig("StoreVersion");
            request.clientApplicationUser    = CustomerID.ToString();

            request.merchantReferenceCode = "Order #: " + OrderNumber.ToString() + " " + Localization.ToNativeDateTimeString(System.DateTime.Now);

            request.merchantID = AppLogic.AppConfig("CYBERSOURCE.merchantID");

            request.voidService = new VoidService();
            request.voidService.voidRequestID = TransID;
            request.voidService.run           = "true";

            result = "ERROR: ";

            try
            {
                ReplyMessage reply = SoapClient.RunTransaction(conf, request);
                if (reply.voidReply.reasonCode == "100")
                {
                    result = AppLogic.ro_OK;
                }
                else
                {
                    result += GetReasonCodeDescription(reply.reasonCode);
                }
            }
            catch (SignException se)
            {
                result += String.Format(
                    "Failed to sign the request with error code {0} and message {1}.", DB.SQuote(se.ErrorCode.ToString()), DB.SQuote(se.Message));
            }
            catch (SoapHeaderException she)
            {
                result += String.Format("A SOAP header exception was returned with fault code {0} and message {1}.", DB.SQuote(she.Code.ToString()), DB.SQuote(she.Message));
            }
            catch (SoapBodyException sbe)
            {
                result += String.Format("A SOAP body exception was returned with fault code {0} and message {1}.", DB.SQuote(sbe.Code.ToString()), DB.SQuote(sbe.Message));
            }
            catch (WebException we)
            {
                result += String.Format("Failed to get a response with status {0} and message {1}", DB.SQuote(we.Status.ToString()), DB.SQuote(we.Message));
            }
            catch (Exception ex)
            {
                result += ex.Message;
            }
            DB.ExecuteSQL("update orders set VoidTXResult=" + DB.SQuote(result) + " where OrderNumber=" + OrderNumber.ToString());

            return(result);
        }
Ejemplo n.º 47
0
 public abstract void Publish(ReplyMessage reply);
Ejemplo n.º 48
0
 private void SendReply(string replyQueueName, IBasicProperties responseProperties, ReplyMessage response)
 {
     _channel.BasicPublish(string.Empty, replyQueueName, responseProperties, response.ToByteArray());
 }