Ejemplo n.º 1
0
        public void OptionalRequestLevelFields()
        {
            // check enrollment
            ThreeDSecure secureEcom = Secure3dService.CheckEnrollment(card)
                                      .Execute(Secure3dVersion.Two);

            Assert.IsNotNull(secureEcom);

            if (secureEcom.Enrolled.Equals("True"))
            {
                Assert.AreEqual(Secure3dVersion.Two, secureEcom.Version);

                // initiate authentication
                ThreeDSecure initAuth = Secure3dService.InitiateAuthentication(card, secureEcom)
                                        .WithAmount(10.01m)
                                        .WithCurrency("USD")
                                        .WithOrderCreateDate(DateTime.Now)
                                        .WithAddress(billingAddress, AddressType.Billing)
                                        .WithAddress(shippingAddress, AddressType.Shipping)
                                        .WithBrowserData(browserData)
                                        .WithMethodUrlCompletion(MethodUrlCompletion.NO)

                                        // optionals
                                        .WithMerchantInitiatedRequestType(AuthenticationRequestType.RECURRING_TRANSACTION)

                                        .Execute();
                Assert.IsNotNull(initAuth);

                // get authentication data
                secureEcom = Secure3dService.GetAuthenticationData()
                             .WithServerTransactionId(initAuth.ServerTransactionId)
                             .Execute();
                card.ThreeDSecure = secureEcom;

                if (secureEcom.Status.Equals("AUTHENTICATION_SUCCESSFUL"))
                {
                    Transaction response = card.Charge(10.01m)
                                           .WithCurrency("USD")
                                           .Execute();
                    Assert.IsNotNull(response);
                    Assert.AreEqual("00", response.ResponseCode);
                }
                else
                {
                    Assert.Fail("Signature verification failed.");
                }
            }
            else
            {
                Assert.Fail("Card not enrolled.");
            }
        }
Ejemplo n.º 2
0
 private void AssertThreeDSResponse(ThreeDSecure secureEcom, string status)
 {
     Assert.IsNotNull(secureEcom);
     Assert.AreEqual(ENROLLED, secureEcom.Enrolled, "Card not enrolled");
     Assert.AreEqual(Secure3dVersion.Two, secureEcom.Version);
     Assert.AreEqual(status, secureEcom.Status);
     Assert.IsNotNull(secureEcom.IssuerAcsUrl);
     Assert.IsNotNull(secureEcom.PayerAuthenticationRequest);
     Assert.IsNotNull(secureEcom.ChallengeReturnUrl);
     Assert.IsNotNull(secureEcom.MessageType);
     Assert.IsNotNull(secureEcom.SessionDataFieldName);
     Assert.IsNull(secureEcom.Eci);
 }
Ejemplo n.º 3
0
        public bool VerifySignature(string authorizationResponse, decimal?amount, string currency, string orderId, string configName = "default")
        {
            // ensure we have an object
            if (ThreeDSecure == null)
            {
                ThreeDSecure = new ThreeDSecure();
            }

            ThreeDSecure.Amount   = amount;
            ThreeDSecure.Currency = currency;
            ThreeDSecure.OrderId  = orderId;

            return(VerifySignature(authorizationResponse, null, configName));
        }
Ejemplo n.º 4
0
        public void FullCycle_v2_with_phone_number_validation()
        {
            // check enrollment
            ThreeDSecure secureEcom = Secure3dService.CheckEnrollment(card)
                                      .Execute(Secure3dVersion.Two);

            Assert.IsNotNull(secureEcom);

            if (secureEcom.Enrolled.Equals("True"))
            {
                Assert.AreEqual(Secure3dVersion.Two, secureEcom.Version);

                // initiate authentication
                ThreeDSecure initAuth = Secure3dService.InitiateAuthentication(card, secureEcom)
                                        .WithAmount(10.01m)
                                        .WithCurrency("USD")
                                        .WithMobileNumber("+54", "(0341) 156-123456")
                                        .WithHomeNumber("+54", "(0341) 156-456789")
                                        .WithWorkNumber("+54", "(0341) 156-654321")
                                        .WithOrderCreateDate(DateTime.Now)
                                        .WithAddress(billingAddress, AddressType.Billing)
                                        .WithAddress(shippingAddress, AddressType.Shipping)
                                        .WithBrowserData(browserData)
                                        .Execute();
                Assert.IsNotNull(initAuth);

                // get authentication data
                secureEcom = Secure3dService.GetAuthenticationData()
                             .WithServerTransactionId(initAuth.ServerTransactionId)
                             .Execute();
                card.ThreeDSecure = secureEcom;

                if (secureEcom.Status.Equals("AUTHENTICATION_SUCCESSFUL"))
                {
                    Transaction response = card.Charge(10.01m)
                                           .WithCurrency("USD")
                                           .Execute();
                    Assert.IsNotNull(response);
                    Assert.AreEqual("00", response.ResponseCode);
                }
                else
                {
                    Assert.Fail("Signature verification Assert.Failed.");
                }
            }
            else
            {
                Assert.Fail("Card not enrolled.");
            }
        }
Ejemplo n.º 5
0
        public void FullCycle_v1()
        {
            CreditCardData card = new CreditCardData {
                Number         = "4012001037141112",
                ExpMonth       = 12,
                ExpYear        = 2025,
                CardHolderName = "John Smith"
            };

            ThreeDSecure secureEcom = Secure3dService.CheckEnrollment(card)
                                      .WithAmount(1m)
                                      .WithCurrency("USD")
                                      .Execute(Secure3dVersion.One);

            Assert.AreEqual(Secure3dVersion.One, secureEcom.Version);

            if (secureEcom.Enrolled.Equals("Y"))
            {
                // authenticate
                ThreeDSecureAcsClient authClient = new ThreeDSecureAcsClient(secureEcom.IssuerAcsUrl);
                var authResponse = authClient.Authenticate(secureEcom.PayerAuthenticationRequest, secureEcom.MerchantData.ToString());

                string payerAuthenticationResponse = authResponse.pares;
                MerchantDataCollection md          = MerchantDataCollection.Parse(authResponse.md);

                // verify signature through the service and affix to the card object
                secureEcom = Secure3dService.GetAuthenticationData()
                             .WithPayerAuthenticationResponse(payerAuthenticationResponse)
                             .WithMerchantData(md)
                             .Execute();
                card.ThreeDSecure = secureEcom;

                if (secureEcom.Status.Equals("Y"))
                {
                    Transaction response = card.Charge().Execute();
                    Assert.IsNotNull(response);
                    Assert.AreEqual("00", response.ResponseCode);
                }
                else
                {
                    Assert.Fail("Signature verification Assert.Failed.");
                }
            }
            else
            {
                Assert.Fail("Card not enrolled.");
            }
        }
Ejemplo n.º 6
0
        public void FullCycle_v1()
        {
            card = new CreditCardData {
                Number         = "4012001037141112",
                ExpMonth       = 12,
                ExpYear        = 2025,
                CardHolderName = "John Doe",
            };

            // Check enrollment
            ThreeDSecure secureEcom = Secure3dService.CheckEnrollment(card)
                                      .WithCurrency("USD")
                                      .WithAmount(10.01m)
                                      .Execute(Secure3dVersion.Any);

            Assert.IsNotNull(secureEcom);

            if (secureEcom.Enrolled.Equals("ENROLLED"))
            {
                Assert.AreEqual(Secure3dVersion.One, secureEcom.Version);

                // Get authentication data
                secureEcom = Secure3dService.GetAuthenticationData()
                             .WithServerTransactionId(secureEcom.ServerTransactionId)
                             .Execute();

                card.ThreeDSecure = secureEcom;

                if (secureEcom.Status.Equals("SUCCESS_AUTHENTICATED"))
                {
                    Transaction response = card.Charge(10.01m)
                                           .WithCurrency("USD")
                                           .Execute();
                    Assert.IsNotNull(response);
                    Assert.AreEqual(SUCCESS, response?.ResponseCode);
                    Assert.AreEqual(GetMapping(TransactionStatus.Captured), response?.ResponseMessage);
                }
                else
                {
                    Assert.Fail("Signature verification Assert.Failed.");
                }
            }
            else
            {
                Assert.Fail("Card not enrolled.");
            }
        }
Ejemplo n.º 7
0
        public bool VerifySignature(string authorizationResponse, MerchantDataCollection merchantData = null, string configName = "default")
        {
            // ensure we have an object
            if (ThreeDSecure == null)
            {
                ThreeDSecure = new ThreeDSecure();
            }

            // if we have some merchantData use it
            if (merchantData != null)
            {
                ThreeDSecure.MerchantData = merchantData;
            }

            Transaction response = new ManagementBuilder(TransactionType.VerifySignature)
                                   .WithAmount(ThreeDSecure.Amount)
                                   .WithCurrency(ThreeDSecure.Currency)
                                   .WithPayerAuthenticationResponse(authorizationResponse)
                                   .WithPaymentMethod(new TransactionReference {
                OrderId = ThreeDSecure.OrderId
            })
                                   .Execute(configName);

            ThreeDSecure.Status    = response.ThreeDSecure.Status;
            ThreeDSecure.Cavv      = response.ThreeDSecure.Cavv;
            ThreeDSecure.Algorithm = response.ThreeDSecure.Algorithm;
            ThreeDSecure.Xid       = response.ThreeDSecure.Xid;

            if (new List <string> {
                "A", "Y"
            }.Contains(ThreeDSecure.Status) && response.ResponseCode == "00")
            {
                ThreeDSecure.Eci = response.ThreeDSecure.Eci;
                return(true);
            }
            else
            {
                ThreeDSecure.Eci = CardType == "MC" ? 0 : 7;
                return(false);
            }
        }
Ejemplo n.º 8
0
        public void FullCycle_v2_EOS_ForceSecure()
        {
            // check enrollment
            ThreeDSecure secureEcom = Secure3dService.CheckEnrollment(card)
                                      .Execute(Secure3dVersion.Two);

            Assert.IsNotNull(secureEcom);

            if (secureEcom.Enrolled.Equals("True"))
            {
                Assert.AreEqual(Secure3dVersion.Two, secureEcom.Version);

                // initiate authentication
                ThreeDSecure initAuth = Secure3dService.InitiateAuthentication(card, secureEcom)
                                        .WithAmount(550m)
                                        .WithCurrency("EUR")
                                        .WithOrderCreateDate(DateTime.Now)
                                        .WithAddress(billingAddress, AddressType.Billing)
                                        .WithAddress(shippingAddress, AddressType.Shipping)
                                        .WithBrowserData(browserData)
                                        .WithEnableExemptionOptimization(true)
                                        .Execute();

                Assert.IsNotNull(initAuth);
                Assert.AreEqual("CHALLENGE_REQUIRED", initAuth.Status);
                Assert.AreEqual(ExemptReason.FORCE_SECURE.ToString(), initAuth.ExemptReason);
                Assert.IsNull(initAuth.ExemptStatus);

                // get authentication data
                secureEcom = Secure3dService.GetAuthenticationData()
                             .WithServerTransactionId(initAuth.ServerTransactionId)
                             .Execute();

                Assert.IsNotNull(secureEcom);
                Assert.AreEqual("CHALLENGE_REQUIRED", secureEcom.Status);
            }
            else
            {
                Assert.Fail("Card not enrolled.");
            }
        }
Ejemplo n.º 9
0
        public void SeansLatestSNAFU()
        {
            // configure client & request settings
            ServicesContainer.ConfigureService(new GatewayConfig {
                MerchantId   = "seanmacdomhnalltest",
                AccountId    = "yoma",
                SharedSecret = "secret",
                ServiceUrl   = "https://api.sandbox.realexpayments.com/epage-remote.cgi"
            });

            // add obtained 3D Secure 2 authentication data
            var threeDSecureData = new ThreeDSecure()
            {
                AuthenticationValue          = "ODQzNjgwNjU0ZjM3N2JmYTg0NTM=",
                DirectoryServerTransactionId = "c272b04f-6e7b-43a2-bb78-90f4fb94aa25",
                Eci            = 5,
                MessageVersion = "2.1.0"
            };

            // supply existing customer/payer ref
            string customerId = "03e28f0e-4cf0-492e-80bd-20ec318e9334";
            // supply existing card/payment method ref
            string paymentId = "cdb398ac-8a0e-49f7-acf0-52a38832cfc9";

            // create the payment method object
            RecurringPaymentMethod paymentMethod = new RecurringPaymentMethod(customerId, paymentId)
            {
                ThreeDSecure = threeDSecureData
            };

            var orderId = "ezJDQjhENTZBLTdCNzNDQw"; // use the same Order ID from the Verify-Enrolled & Verify-Sig
                                                    // create the Authorization with 3D Secure information
            var response = paymentMethod.Charge(99.99m)
                           .WithOrderId(orderId)
                           .WithCurrency("EUR")
                           .Execute();

            Assert.IsNotNull(response);
        }
Ejemplo n.º 10
0
        public void CardHolderEnrolled_Frictionless_v2_Initiate_With_MobileDataAndBrowserData()
        {
            card.Number = GpApi3DSTestCards.CARD_AUTH_SUCCESSFUL_V2_1;

            var secureEcom = Secure3dService.CheckEnrollment(card)
                             .WithCurrency(Currency)
                             .WithAmount(Amount)
                             .WithAuthenticationSource(AuthenticationSource.MOBILE_SDK)
                             .Execute(Secure3dVersion.Two);

            AssertThreeDSResponse(secureEcom, AVAILABLE);
            Assert.AreEqual(ENROLLED, secureEcom.Enrolled);

            ThreeDSecure initAuth =
                Secure3dService
                .InitiateAuthentication(card, secureEcom)
                .WithCurrency(Currency)
                .WithAmount(Amount)
                .WithAuthenticationSource(AuthenticationSource.MOBILE_SDK)
                .WithMethodUrlCompletion(MethodUrlCompletion.YES)
                .WithOrderCreateDate(DateTime.Now)
                .WithAddress(shippingAddress, AddressType.Shipping)
                .WithMobileData(mobileData)
                .WithBrowserData(browserData)
                .Execute(Secure3dVersion.Two);

            Assert.IsNotNull(initAuth);
            Assert.AreEqual(ENROLLED, initAuth.Enrolled);
            Assert.AreEqual(Secure3dVersion.Two, initAuth.Version);
            Assert.AreEqual(SUCCESS_AUTHENTICATED, initAuth.Status);
            Assert.AreEqual("YES", initAuth.LiabilityShift);
            Assert.IsFalse(initAuth.ChallengeMandated);
            Assert.IsNotNull(initAuth.IssuerAcsUrl);
            Assert.IsNotNull(initAuth.PayerAuthenticationRequest);
            Assert.IsNotNull(initAuth.ChallengeReturnUrl);
            Assert.IsNotNull(initAuth.MessageType);
            Assert.IsNotNull(initAuth.SessionDataFieldName);
            Assert.AreEqual("05", initAuth.Eci);
        }
Ejemplo n.º 11
0
        public Transaction ProcessSecure3d(Secure3dBuilder builder)
        {
            TransactionType transType     = builder.TransactionType;
            IPaymentMethod  paymentMethod = builder.PaymentMethod;
            ISecure3d       secure3d      = (ISecure3d)paymentMethod;
            string          timestamp     = DateTime.Now.ToString("yyyy-MM-dd'T'hh:mm:ss.ffffff");

            JsonDoc request = new JsonDoc();

            if (transType.Equals(TransactionType.VerifyEnrolled))
            {
                request.Set("request_timestamp", timestamp);
                request.Set("merchant_id", MerchantId);
                request.Set("account_id", AccountId);
                request.Set("method_notification_url", MethodNotificationUrl);

                string hashValue = string.Empty;
                if (paymentMethod is CreditCardData cardData)
                {
                    request.Set("number", cardData.Number);
                    request.Set("scheme", MapCardScheme(cardData.CardType.ToUpper()));
                    hashValue = cardData.Number;
                }
                else if (paymentMethod is RecurringPaymentMethod storedCard)
                {
                    request.Set("payer_reference", storedCard.CustomerKey);
                    request.Set("payment_method_reference", storedCard.Key);
                    hashValue = storedCard.CustomerKey;
                }

                string hash = GenerationUtils.GenerateHash(SharedSecret, timestamp, MerchantId, hashValue);
                SetAuthHeader(hash);

                string rawResponse = DoTransaction(HttpMethod.Post, "protocol-versions", request.ToString());
                return(MapResponse(rawResponse));
            }
            else if (transType.Equals(TransactionType.VerifySignature))
            {
                string hash = GenerationUtils.GenerateHash(SharedSecret, timestamp, MerchantId, builder.ServerTransactionId);
                SetAuthHeader(hash);

                var queryValues = new Dictionary <string, string>();
                queryValues.Add("merchant_id", MerchantId);
                queryValues.Add("request_timestamp", timestamp);

                string rawResponse = DoTransaction(HttpMethod.Get, string.Format("authentications/{0}", builder.ServerTransactionId), null, queryValues);
                return(MapResponse(rawResponse));
            }
            else if (transType.Equals(TransactionType.InitiateAuthentication))
            {
                string orderId = builder.OrderId;
                if (string.IsNullOrEmpty(orderId))
                {
                    orderId = GenerationUtils.GenerateOrderId();
                }
                ThreeDSecure secureEcom = secure3d.ThreeDSecure;

                request.Set("request_timestamp", timestamp);
                request.Set("authentication_source", builder.AuthenticationSource.ToString());
                request.Set("authentication_request_type", builder.AuthenticationRequestType.ToString());
                request.Set("message_category", builder.MessageCategory.ToString());
                request.Set("message_version", "2.1.0");
                request.Set("server_trans_id", secureEcom.ServerTransactionId);
                request.Set("merchant_id", MerchantId);
                request.Set("account_id", AccountId);
                request.Set("challenge_notification_url", ChallengeNotificationUrl);
                request.Set("method_url_completion", builder.MethodUrlCompletion.ToString());
                request.Set("merchant_contact_url", MerchantContactUrl);
                request.Set("merchant_initiated_request_type", builder.MerchantInitiatedRequestType?.ToString());
                request.Set("whitelist_status", builder.WhitelistStatus);
                request.Set("decoupled_flow_request", builder.DecoupledFlowRequest);
                request.Set("decoupled_flow_timeout", builder.DecoupledFlowTimeout);
                request.Set("decoupled_notification_url", builder.DecoupledNotificationUrl);
                request.Set("enable_exemption_optimization", builder.EnableExemptionOptimization);

                // card details
                string  hashValue  = string.Empty;
                JsonDoc cardDetail = request.SubElement("card_detail");
                if (paymentMethod is CreditCardData cardData)
                {
                    hashValue = cardData.Number;
                    cardDetail.Set("number", cardData.Number);
                    cardDetail.Set("scheme", cardData.CardType.ToUpper());
                    cardDetail.Set("expiry_month", cardData.ExpMonth.ToString());
                    cardDetail.Set("expiry_year", cardData.ExpYear.ToString().Substring(2));
                    cardDetail.Set("full_name", cardData.CardHolderName);

                    if (!string.IsNullOrEmpty(cardData.CardHolderName))
                    {
                        string[] names = cardData.CardHolderName.Split(' ');
                        if (names.Length >= 1)
                        {
                            cardDetail.Set("first_name", names[0]);
                        }
                        if (names.Length >= 2)
                        {
                            cardDetail.Set("last_name", string.Join(" ", names.Skip(1)));
                        }
                    }
                }
                else if (paymentMethod is RecurringPaymentMethod storedCard)
                {
                    hashValue = storedCard.CustomerKey;
                    cardDetail.Set("payer_reference", storedCard.CustomerKey);
                    cardDetail.Set("payment_method_reference", storedCard.Key);
                }

                // order details
                JsonDoc order = request.SubElement("order");
                order.Set("amount", builder.Amount.ToNumericCurrencyString());
                order.Set("currency", builder.Currency);
                order.Set("id", orderId);
                order.Set("address_match_indicator", builder.AddressMatchIndicator ? "true" : "false");
                order.Set("date_time_created", builder.OrderCreateDate?.ToString("yyyy-MM-dd'T'hh:mm'Z'"));
                order.Set("gift_card_count", builder.GiftCardCount);
                order.Set("gift_card_currency", builder.GiftCardCurrency);
                order.Set("gift_card_amount", builder.GiftCardAmount.ToNumericCurrencyString());
                order.Set("delivery_email", builder.DeliveryEmail);
                order.Set("delivery_timeframe", builder.DeliveryTimeframe?.ToString());
                order.Set("shipping_method", builder.ShippingMethod?.ToString());
                order.Set("shipping_name_matches_cardholder_name", builder.ShippingNameMatchesCardHolderName);
                order.Set("preorder_indicator", builder.PreOrderIndicator?.ToString());
                order.Set("reorder_indicator", builder.ReorderIndicator?.ToString());
                order.Set("transaction_type", builder.OrderTransactionType?.ToString());
                order.Set("preorder_availability_date", builder.PreOrderAvailabilityDate?.ToString("yyyy-MM-dd"));

                // shipping address
                Address shippingAddress = builder.ShippingAddress;
                if (shippingAddress != null)
                {
                    JsonDoc shippingAddressElement = order.SubElement("shipping_address");
                    shippingAddressElement.Set("line1", shippingAddress.StreetAddress1);
                    shippingAddressElement.Set("line2", shippingAddress.StreetAddress2);
                    shippingAddressElement.Set("line3", shippingAddress.StreetAddress3);
                    shippingAddressElement.Set("city", shippingAddress.City);
                    shippingAddressElement.Set("postal_code", shippingAddress.PostalCode);
                    shippingAddressElement.Set("state", shippingAddress.State);
                    shippingAddressElement.Set("country", shippingAddress.CountryCode);
                }

                // payer
                JsonDoc payer = request.SubElement("payer");
                payer.Set("email", builder.CustomerEmail);
                payer.Set("id", builder.CustomerAccountId);
                payer.Set("account_age", builder.AccountAgeIndicator?.ToString());
                payer.Set("account_creation_date", builder.AccountCreateDate?.ToString("yyyy-MM-dd"));
                payer.Set("account_change_indicator", builder.AccountChangeIndicator?.ToString());
                payer.Set("account_change_date", builder.AccountChangeDate?.ToString("yyyy-MM-dd"));
                payer.Set("account_password_change_indicator", builder.PasswordChangeIndicator?.ToString());
                payer.Set("account_password_change_date", builder.PasswordChangeDate?.ToString("yyyy-MM-dd"));
                payer.Set("payment_account_age_indicator", builder.PaymentAgeIndicator?.ToString());
                payer.Set("payment_account_creation_date", builder.PaymentAccountCreateDate?.ToString("yyyy-MM-dd"));
                payer.Set("purchase_count_last_6months", builder.NumberOfPurchasesInLastSixMonths);
                payer.Set("transaction_count_last_24hours", builder.NumberOfTransactionsInLast24Hours);
                payer.Set("transaction_count_last_year", builder.NumberOfTransactionsInLastYear);
                payer.Set("provision_attempt_count_last_24hours", builder.NumberOfAddCardAttemptsInLast24Hours);
                payer.Set("shipping_address_creation_indicator", builder.ShippingAddressUsageIndicator?.ToString());
                payer.Set("shipping_address_creation_date", builder.ShippingAddressCreateDate?.ToString("yyyy-MM-dd"));

                // suspicious activity
                if (builder.PreviousSuspiciousActivity != null)
                {
                    payer.Set("suspicious_account_activity", builder.PreviousSuspiciousActivity.Value ? "SUSPICIOUS_ACTIVITY" : "NO_SUSPICIOUS_ACTIVITY");
                }

                // home phone
                if (!string.IsNullOrEmpty(builder.HomeNumber))
                {
                    payer.SubElement("home_phone")
                    .Set("country_code", builder.HomeCountryCode)
                    .Set("subscriber_number", builder.HomeNumber);
                }

                // work phone
                if (!string.IsNullOrEmpty(builder.WorkNumber))
                {
                    payer.SubElement("work_phone")
                    .Set("country_code", builder.WorkCountryCode)
                    .Set("subscriber_number", builder.WorkNumber);
                }

                // payer login data
                if (builder.HasPayerLoginData)
                {
                    request.SubElement("payer_login_data")
                    .Set("authentication_data", builder.CustomerAuthenticationData)
                    .Set("authentication_timestamp", builder.CustomerAuthenticationTimestamp?.ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'"))
                    .Set("authentication_type", builder.CustomerAuthenticationMethod?.ToString());
                }

                // prior authentication data
                if (builder.HasPriorAuthenticationData)
                {
                    request.SubElement("payer_prior_three_ds_authentication_data")
                    .Set("authentication_method", builder.PriorAuthenticationMethod?.ToString())
                    .Set("acs_transaction_id", builder.PriorAuthenticationTransactionId)
                    .Set("authentication_timestamp", builder.PriorAuthenticationTimestamp?.ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'"))
                    .Set("authentication_data", builder.PriorAuthenticationData);
                }

                // recurring authorization data
                if (builder.HasRecurringAuthData)
                {
                    request.SubElement("recurring_authorization_data")
                    .Set("max_number_of_instalments", builder.MaxNumberOfInstallments)
                    .Set("frequency", builder.RecurringAuthorizationFrequency)
                    .Set("expiry_date", builder.RecurringAuthorizationExpiryDate?.ToString("yyyy-MM-dd"));
                }

                // billing details
                Address billingAddress = builder.BillingAddress;
                if (billingAddress != null)
                {
                    JsonDoc billingAddressElement = payer.SubElement("billing_address");
                    billingAddressElement.Set("line1", billingAddress.StreetAddress1);
                    billingAddressElement.Set("line2", billingAddress.StreetAddress2);
                    billingAddressElement.Set("line3", billingAddress.StreetAddress3);
                    billingAddressElement.Set("city", billingAddress.City);
                    billingAddressElement.Set("postal_code", billingAddress.PostalCode);
                    billingAddressElement.Set("state", billingAddress.State);
                    billingAddressElement.Set("country", billingAddress.CountryCode);
                }

                // mobile phone
                if (!string.IsNullOrEmpty(builder.MobileNumber))
                {
                    JsonDoc mobilePhone = payer.SubElement("mobile_phone");
                    mobilePhone.Set("country_code", builder.MobileCountryCode);
                    mobilePhone.Set("subscriber_number", builder.MobileNumber);
                }

                // browser_data
                BrowserData broswerData = builder.BrowserData;
                if (broswerData != null)
                {
                    JsonDoc browserDataElement = request.SubElement("browser_data");
                    browserDataElement.Set("accept_header", broswerData.AcceptHeader);
                    browserDataElement.Set("color_depth", broswerData.ColorDepth.ToString());
                    browserDataElement.Set("ip", broswerData.IpAddress);
                    browserDataElement.Set("java_enabled", broswerData.JavaEnabled);
                    browserDataElement.Set("javascript_enabled", broswerData.JavaScriptEnabled);
                    browserDataElement.Set("language", broswerData.Language);
                    browserDataElement.Set("screen_height", broswerData.ScreenHeight);
                    browserDataElement.Set("screen_width", broswerData.ScreenWidth);
                    browserDataElement.Set("challenge_window_size", broswerData.ChallengeWindowSize.ToString());
                    browserDataElement.Set("timezone", broswerData.Timezone);
                    browserDataElement.Set("user_agent", broswerData.UserAgent);
                }

                // mobile fields
                if (builder.HasMobileFields)
                {
                    JsonDoc sdkInformationElement = request.SubElement("sdk_information")
                                                    .Set("application_id", builder.ApplicationId)
                                                    .Set("ephemeral_public_key", builder.EphemeralPublicKey)
                                                    .Set("maximum_timeout", builder.MaximumTimeout)
                                                    .Set("reference_number", builder.ReferenceNumber)
                                                    .Set("sdk_trans_id", builder.SdkTransactionId)
                                                    .Set("encoded_data", builder.EncodedData)
                    ;

                    // device render options
                    if (builder.SdkInterface != null || builder.SdkUiTypes != null)
                    {
                        var dro = sdkInformationElement.SubElement("device_render_options");
                        dro.Set("sdk_interface", builder.SdkInterface?.ToString());
                        if (builder.SdkUiTypes != null)
                        {
                            var uiTypes = new List <string>();
                            foreach (var sdkuiType in builder.SdkUiTypes)
                            {
                                uiTypes.Add(sdkuiType.ToString());
                            }
                            dro.Set("sdk_ui_type", uiTypes.ToArray());
                        }
                    }
                }

                string hash = GenerationUtils.GenerateHash(SharedSecret, timestamp, MerchantId, hashValue, secureEcom.ServerTransactionId);
                SetAuthHeader(hash);

                string rawResponse = DoTransaction(HttpMethod.Post, "authentications", request.ToString());
                return(MapResponse(rawResponse));
            }

            throw new ApiException(string.Format("Unknown transaction type {0}.", transType));
        }
Ejemplo n.º 12
0
        private Transaction MapResponse(string rawResponse)
        {
            JsonDoc doc = JsonDoc.Parse(rawResponse);

            ThreeDSecure secureEcom = new ThreeDSecure();

            // check enrolled
            secureEcom.ServerTransactionId = doc.GetValue <string>("server_trans_id");
            if (doc.Has("enrolled"))
            {
                secureEcom.Enrolled = doc.GetValue <string>("enrolled");
            }
            secureEcom.IssuerAcsUrl = doc.GetValue <string>("method_url", "challenge_request_url");

            // get authentication data
            secureEcom.AcsTransactionId             = doc.GetValue <string>("acs_trans_id");
            secureEcom.DirectoryServerTransactionId = doc.GetValue <string>("ds_trans_id");
            secureEcom.AuthenticationType           = doc.GetValue <string>("authentication_type");
            secureEcom.AuthenticationValue          = doc.GetValue <string>("authentication_value");
            secureEcom.Eci                        = doc.GetValue <int>("eci");
            secureEcom.Status                     = doc.GetValue <string>("status");
            secureEcom.StatusReason               = doc.GetValue <string>("status_reason");
            secureEcom.AuthenticationSource       = doc.GetValue <string>("authentication_source");
            secureEcom.MessageCategory            = doc.GetValue <string>("message_category");
            secureEcom.MessageVersion             = doc.GetValue <string>("message_version");
            secureEcom.AcsInfoIndicator           = doc.GetArray <string>("acs_info_indicator");
            secureEcom.DecoupledResponseIndicator = doc.GetValue <string>("decoupled_response_indicator");
            secureEcom.WhitelistStatus            = doc.GetValue <string>("whitelist_status");
            secureEcom.ExemptReason               = doc.GetValue <string>("eos_reason");
            if (secureEcom.ExemptReason == ExemptReason.APPLY_EXEMPTION.ToString())
            {
                secureEcom.ExemptStatus = ExemptStatus.TRANSACTION_RISK_ANALYSIS;
            }

            // challenge mandated
            if (doc.Has("challenge_mandated"))
            {
                secureEcom.ChallengeMandated = doc.GetValue <bool>("challenge_mandated");
            }

            // initiate authentication
            secureEcom.CardHolderResponseInfo = doc.GetValue <string>("cardholder_response_info");

            // device_render_options
            if (doc.Has("device_render_options"))
            {
                JsonDoc renderOptions = doc.Get("device_render_options");
                secureEcom.SdkInterface = renderOptions.GetValue <string>("sdk_interface");
                secureEcom.SdkUiType    = renderOptions.GetArray <string>("sdk_ui_type");
            }

            // message_extension
            if (doc.Has("message_extension"))
            {
                secureEcom.MessageExtensions = new List <MessageExtension>();
                foreach (JsonDoc messageExtension in doc.GetEnumerator("message_extension"))
                {
                    MessageExtension msgExtension = new MessageExtension
                    {
                        CriticalityIndicator = messageExtension.GetValue <string>("criticality_indicator"),
                        MessageExtensionData = messageExtension.GetValue <JsonDoc>("data")?.ToString(),
                        MessageExtensionId   = messageExtension.GetValue <string>("id"),
                        MessageExtensionName = messageExtension.GetValue <string>("name")
                    };
                    secureEcom.MessageExtensions.Add(msgExtension);
                }
            }

            // versions
            secureEcom.DirectoryServerEndVersion   = doc.GetValue <string>("ds_protocol_version_end");
            secureEcom.DirectoryServerStartVersion = doc.GetValue <string>("ds_protocol_version_start");
            secureEcom.AcsEndVersion   = doc.GetValue <string>("acs_protocol_version_end");
            secureEcom.AcsStartVersion = doc.GetValue <string>("acs_protocol_version_start");

            // payer authentication request
            if (doc.Has("method_data"))
            {
                JsonDoc methodData = doc.Get("method_data");
                secureEcom.PayerAuthenticationRequest = methodData.GetValue <string>("encoded_method_data");
            }
            else if (doc.Has("encoded_creq"))
            {
                secureEcom.PayerAuthenticationRequest = doc.GetValue <string>("encoded_creq");
            }

            Transaction response = new Transaction {
                ThreeDSecure = secureEcom
            };

            return(response);
        }
Ejemplo n.º 13
0
 public RealEx3DAuthRequest(string secret, string merchantId, string account, string orderId, Amount amount, Card card, TssInfo tssInfo, ThreeDSecure threeDSecure, bool autoSettle, string custNum, string prodId, string varRef, Comments comments)
     : base(secret, merchantId, account, orderId, amount, card, tssInfo, autoSettle, custNum, prodId, varRef, comments)
 {
     Mpi = new Mpi(threeDSecure.Cavv, threeDSecure.Xid, threeDSecure.Eci);
 }
        public async void Example()
        {
#pragma warning disable 0168
            using (Client client = GetClient())
            {
                Card card = new Card();
                card.CardNumber     = "4567350000427977";
                card.CardholderName = "Wile E. Coyote";
                card.Cvv            = "123";
                card.ExpiryDate     = "1220";

                RedirectionData redirectionData = new RedirectionData();
                redirectionData.ReturnUrl = "https://hostname.myownwebsite.url";

                ThreeDSecure threeDSecure = new ThreeDSecure();
                threeDSecure.AuthenticationFlow  = "browser";
                threeDSecure.ChallengeCanvasSize = "600x400";
                threeDSecure.ChallengeIndicator  = "challenge-requested";
                threeDSecure.ExemptionRequest    = "none";
                threeDSecure.RedirectionData     = redirectionData;
                threeDSecure.SkipAuthentication  = false;

                CardPaymentMethodSpecificInput cardPaymentMethodSpecificInput = new CardPaymentMethodSpecificInput();
                cardPaymentMethodSpecificInput.Card        = card;
                cardPaymentMethodSpecificInput.IsRecurring = false;
                cardPaymentMethodSpecificInput.MerchantInitiatedReasonIndicator = "delayedCharges";
                cardPaymentMethodSpecificInput.PaymentProductId   = 1;
                cardPaymentMethodSpecificInput.ThreeDSecure       = threeDSecure;
                cardPaymentMethodSpecificInput.TransactionChannel = "ECOMMERCE";

                AmountOfMoney amountOfMoney = new AmountOfMoney();
                amountOfMoney.Amount       = 2980L;
                amountOfMoney.CurrencyCode = "EUR";

                Address billingAddress = new Address();
                billingAddress.AdditionalInfo = "b";
                billingAddress.City           = "Monument Valley";
                billingAddress.CountryCode    = "US";
                billingAddress.HouseNumber    = "13";
                billingAddress.State          = "Utah";
                billingAddress.Street         = "Desertroad";
                billingAddress.Zip            = "84536";

                CompanyInformation companyInformation = new CompanyInformation();
                companyInformation.Name      = "Acme Labs";
                companyInformation.VatNumber = "1234AB5678CD";

                ContactDetails contactDetails = new ContactDetails();
                contactDetails.EmailAddress = "*****@*****.**";
                contactDetails.FaxNumber    = "+1234567891";
                contactDetails.PhoneNumber  = "+1234567890";

                BrowserData browserData = new BrowserData();
                browserData.ColorDepth   = 24;
                browserData.JavaEnabled  = false;
                browserData.ScreenHeight = "1200";
                browserData.ScreenWidth  = "1920";

                CustomerDevice device = new CustomerDevice();
                device.AcceptHeader             = "texthtml,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                device.BrowserData              = browserData;
                device.IpAddress                = "123.123.123.123";
                device.Locale                   = "en-US";
                device.TimezoneOffsetUtcMinutes = "420";
                device.UserAgent                = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1 Safari/605.1.15";

                PersonalName name = new PersonalName();
                name.FirstName     = "Wile";
                name.Surname       = "Coyote";
                name.SurnamePrefix = "E.";
                name.Title         = "Mr.";

                PersonalInformation personalInformation = new PersonalInformation();
                personalInformation.DateOfBirth = "19490917";
                personalInformation.Gender      = "male";
                personalInformation.Name        = name;

                Customer customer = new Customer();
                customer.AccountType         = "none";
                customer.BillingAddress      = billingAddress;
                customer.CompanyInformation  = companyInformation;
                customer.ContactDetails      = contactDetails;
                customer.Device              = device;
                customer.Locale              = "en_US";
                customer.MerchantCustomerId  = "1234";
                customer.PersonalInformation = personalInformation;

                OrderInvoiceData invoiceData = new OrderInvoiceData();
                invoiceData.InvoiceDate   = "20140306191500";
                invoiceData.InvoiceNumber = "000000123";

                OrderReferences references = new OrderReferences();
                references.Descriptor        = "Fast and Furry-ous";
                references.InvoiceData       = invoiceData;
                references.MerchantOrderId   = 123456L;
                references.MerchantReference = "AcmeOrder0001";

                PersonalName shippingName = new PersonalName();
                shippingName.FirstName = "Road";
                shippingName.Surname   = "Runner";
                shippingName.Title     = "Miss";

                AddressPersonal address = new AddressPersonal();
                address.AdditionalInfo = "Suite II";
                address.City           = "Monument Valley";
                address.CountryCode    = "US";
                address.HouseNumber    = "1";
                address.Name           = shippingName;
                address.State          = "Utah";
                address.Street         = "Desertroad";
                address.Zip            = "84536";

                Shipping shipping = new Shipping();
                shipping.Address = address;

                IList <LineItem> items = new List <LineItem>();

                AmountOfMoney item1AmountOfMoney = new AmountOfMoney();
                item1AmountOfMoney.Amount       = 2500L;
                item1AmountOfMoney.CurrencyCode = "EUR";

                LineItemInvoiceData item1InvoiceData = new LineItemInvoiceData();
                item1InvoiceData.Description  = "ACME Super Outfit";
                item1InvoiceData.NrOfItems    = "1";
                item1InvoiceData.PricePerItem = 2500L;

                LineItem item1 = new LineItem();
                item1.AmountOfMoney = item1AmountOfMoney;
                item1.InvoiceData   = item1InvoiceData;

                items.Add(item1);

                AmountOfMoney item2AmountOfMoney = new AmountOfMoney();
                item2AmountOfMoney.Amount       = 480L;
                item2AmountOfMoney.CurrencyCode = "EUR";

                LineItemInvoiceData item2InvoiceData = new LineItemInvoiceData();
                item2InvoiceData.Description  = "Aspirin";
                item2InvoiceData.NrOfItems    = "12";
                item2InvoiceData.PricePerItem = 40L;

                LineItem item2 = new LineItem();
                item2.AmountOfMoney = item2AmountOfMoney;
                item2.InvoiceData   = item2InvoiceData;

                items.Add(item2);

                ShoppingCart shoppingCart = new ShoppingCart();
                shoppingCart.Items = items;

                Order order = new Order();
                order.AmountOfMoney = amountOfMoney;
                order.Customer      = customer;
                order.References    = references;
                order.Shipping      = shipping;
                order.ShoppingCart  = shoppingCart;

                CreatePaymentRequest body = new CreatePaymentRequest();
                body.CardPaymentMethodSpecificInput = cardPaymentMethodSpecificInput;
                body.Order = order;

                try
                {
                    CreatePaymentResponse response = await client.Merchant("merchantId").Payments().Create(body);
                }
                catch (DeclinedPaymentException e)
                {
                    HandleDeclinedPayment(e.CreatePaymentResult);
                }
                catch (ApiException e)
                {
                    HandleApiErrors(e.Errors);
                }
            }
#pragma warning restore 0168
        }
Ejemplo n.º 15
0
        public IActionResult IniciarAuth([FromQuery] Tarjeta detalles, [FromQuery] NavegadorCliente navClient, [FromQuery] RespuestaVersion3DS2 responseACSVersion)
        {
            // Configuramos los datos de nuestro comercio. Los datos son proporcionados por el equipo de Addon Payments,
            // en caso de duda debe llamar al 914 353 028 e indicar su número de comercio o Merchant ID
            ServicesContainer.ConfigureService(new GatewayConfig
            {
                MerchantId               = "addonnettest",
                AccountId                = "3ds2",
                SharedSecret             = "secret",
                MethodNotificationUrl    = "https://dominio.com/notificacion3ds",
                ChallengeNotificationUrl = "https://dominio.com/notificacionAcs",
                MerchantContactUrl       = "https://www.dominio.com/about",
                Secure3dVersion          = Secure3dVersion.Two
            });

            // Tarjetas de prueba
            // Frictionless: 4263970000005262
            // Challenge: 4012001038488884
            var card = new CreditCardData
            {
                Number         = detalles.cardNumber,
                ExpMonth       = detalles.month,
                ExpYear        = detalles.year,
                Cvn            = detalles.cvn,
                CardHolderName = detalles.cardholderName
            };

            // Indicamos la dirección de facturación
            Address billingAddress = new Address
            {
                StreetAddress1 = "Apartment 852",
                StreetAddress2 = "Complex 741",
                StreetAddress3 = "Unit 4",
                City           = "Chicago",
                PostalCode     = "50001",
                State          = "IL",
                CountryCode    = "840"
            };

            // Indicamos la dirección de envío
            Address shippingAddress = new Address
            {
                StreetAddress1 = "Flat 456",
                StreetAddress2 = "House 789",
                StreetAddress3 = "Basement Flat",
                City           = "Halifax",
                PostalCode     = "W5 9HR",
                CountryCode    = "826"
            };

            // Indicamos los datos del navegaddor del cliente
            BrowserData browserData = new BrowserData
            {
                AcceptHeader        = "text/html,application/xhtml+xml,application/xml;q=9,image/webp,img/apng,/;q=0.8",
                ColorDepth          = navClient.colorDepth,
                IpAddress           = "123.123.123.123",
                JavaEnabled         = navClient.javaEnabled,
                Language            = navClient.browserLanguage,
                ScreenHeight        = navClient.screenHeight,
                ScreenWidth         = navClient.screenWidth,
                ChallengeWindowSize = ChallengeWindowSize.FULL_SCREEN,
                Timezone            = navClient.browserTimezoneZoneOffset,
                UserAgent           = navClient.userAgent
            };


            ThreeDSecure threeDSecureData = new ThreeDSecure
            {
                ServerTransactionId = responseACSVersion.serverTransactionId
            };

            try
            {
                threeDSecureData = Secure3dService.InitiateAuthentication(card, threeDSecureData)
                                   .WithAmount(10.01m)
                                   .WithCurrency("EUR")
                                   .WithOrderCreateDate(DateTime.Parse("2019-09-09T11:19:12"))
                                   .WithCustomerEmail("*****@*****.**")
                                   .WithAddress(billingAddress, AddressType.Billing)
                                   .WithAddress(shippingAddress, AddressType.Shipping)
                                   .WithBrowserData(browserData)
                                   .WithMethodUrlCompletion(MethodUrlCompletion.YES)
                                   .WithMobileNumber("44", "7123456789")
                                   .Execute();

                // Informamos al cliente
                RespuestaVersion3DS2 respuesta = new RespuestaVersion3DS2
                {
                    acsEndVersion          = threeDSecureData.AcsEndVersion,
                    acsStartVersion        = threeDSecureData.AcsStartVersion,
                    acsTransactionId       = threeDSecureData.AcsTransactionId,
                    algorithm              = threeDSecureData.Algorithm,
                    authenticationSource   = threeDSecureData.AuthenticationSource,
                    authenticationType     = threeDSecureData.AuthenticationType,
                    authenticationValue    = threeDSecureData.AuthenticationValue,
                    cardHolderResponseInfo = threeDSecureData.CardHolderResponseInfo,
                    cavv = threeDSecureData.Cavv,
                    challengeMandated            = threeDSecureData.ChallengeMandated,
                    criticalityIndicator         = threeDSecureData.CriticalityIndicator,
                    directoryServerEndVersion    = threeDSecureData.DirectoryServerEndVersion,
                    directoryServerStartVersion  = threeDSecureData.DirectoryServerStartVersion,
                    directoryServerTransactionId = threeDSecureData.DirectoryServerTransactionId,
                    eci                        = threeDSecureData.Eci,
                    enrolled                   = threeDSecureData.Enrolled,
                    issuerAcsUrl               = threeDSecureData.IssuerAcsUrl,
                    messageCategory            = threeDSecureData.MessageCategory,
                    messageExtensionId         = threeDSecureData.MessageExtensionId,
                    messageExtensionName       = threeDSecureData.MessageExtensionName,
                    messageVersion             = threeDSecureData.MessageVersion,
                    payerAuthenticationRequest = threeDSecureData.PayerAuthenticationRequest,
                    paymentDataSource          = threeDSecureData.PaymentDataSource,
                    paymentDataType            = threeDSecureData.PaymentDataType,
                    sdkInterface               = threeDSecureData.SdkInterface,
                    sdkUiType                  = threeDSecureData.SdkUiType,
                    serverTransactionId        = threeDSecureData.ServerTransactionId,
                    status                     = threeDSecureData.Status,
                    statusReason               = threeDSecureData.StatusReason,
                    xid                        = threeDSecureData.Xid
                };

                return(Ok(respuesta));
            }

            catch (ApiException exce)
            {
                return(BadRequest(exce));
                // TODO: agregue su control de excepciones aquí
            }
        }
Ejemplo n.º 16
0
 public ChargeRequestBuilder With3DSecure(ThreeDSecure threeDSecure)
 {
     _threeDSecure = threeDSecure;
     return(this);
 }
Ejemplo n.º 17
0
        static async Task Main(string[] args)
        {
            try
            {
                string paymentProductId = string.Empty;
                do
                {
                    Console.WriteLine("Enter Payment Product Code");
                    Console.WriteLine("Code | Card Type");
                    Console.WriteLine("1    | Visa");
                    Console.WriteLine("2    | Master Card");
                    paymentProductId = Console.ReadLine();
                } while (string.IsNullOrWhiteSpace(paymentProductId) || !new string[] { "1", "2" }.ToList().Contains(paymentProductId));


                Card card = new Card();
                card.CardNumber = "4567350000427977";
                card.Cvv        = "123";
                card.ExpiryDate = "1220";

                ThreeDSecure threeDSecure = new ThreeDSecure();
                threeDSecure.SkipAuthentication = false;

                CardPaymentMethodSpecificInput cardPaymentMethodSpecificInput = new CardPaymentMethodSpecificInput();
                cardPaymentMethodSpecificInput.Card             = card;
                cardPaymentMethodSpecificInput.PaymentProductId = paymentProductId == "2" ? 3 : 1;
                cardPaymentMethodSpecificInput.ThreeDSecure     = threeDSecure;

                AmountOfMoney amountOfMoney = new AmountOfMoney();
                amountOfMoney.Amount       = 1;
                amountOfMoney.CurrencyCode = "USD";

                Address billingAddress = new Address();
                billingAddress.CountryCode = "US";

                Customer customer = new Customer();
                customer.BillingAddress     = billingAddress;
                customer.MerchantCustomerId = "1378";

                Order order = new Order();
                order.AmountOfMoney = amountOfMoney;
                order.Customer      = customer;

                CreatePaymentRequest body = new CreatePaymentRequest();
                body.CardPaymentMethodSpecificInput = cardPaymentMethodSpecificInput;
                body.Order = order;

                try
                {
                    using (Client client = GetClient())
                    {
                        CreatePaymentResponse response = await client.Merchant("1378").Payments().Create(body);

                        Console.WriteLine("Id: " + response.Payment.Id);
                        Console.WriteLine("Status: " + response.Payment.Status);
                        Console.WriteLine("AmountOfMoney: " + response.Payment.PaymentOutput.AmountOfMoney);
                    }
                }
                catch (DeclinedPaymentException e)
                {
                    Console.WriteLine("Error: Payment Declined");
                    foreach (var error in e.Errors)
                    {
                        Console.WriteLine("Code: " + error.Code);
                        Console.WriteLine("PropertyName: " + error.PropertyName);
                        Console.WriteLine("Message: " + error.Message);
                    }
                }
                catch (ApiException e)
                {
                    Console.WriteLine("Error: Unknown error occured");
                    foreach (var error in e.Errors)
                    {
                        Console.WriteLine("Code: " + error.Code);
                        Console.WriteLine("PropertyName: " + error.PropertyName);
                        Console.WriteLine("Message: " + error.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.ReadLine();
        }
Ejemplo n.º 18
0
        public void OptionalPayerLevelFields()
        {
            // check enrollment
            ThreeDSecure secureEcom = Secure3dService.CheckEnrollment(card)
                                      .Execute(Secure3dVersion.Two);

            Assert.IsNotNull(secureEcom);

            if (secureEcom.Enrolled.Equals("True"))
            {
                Assert.AreEqual(Secure3dVersion.Two, secureEcom.Version);

                // initiate authentication
                ThreeDSecure initAuth = Secure3dService.InitiateAuthentication(card, secureEcom)
                                        .WithAmount(250m)
                                        .WithCurrency("USD")
                                        .WithOrderCreateDate(DateTime.Now)
                                        .WithAddress(billingAddress, AddressType.Billing)
                                        .WithAddress(shippingAddress, AddressType.Shipping)
                                        .WithBrowserData(browserData)
                                        .WithMethodUrlCompletion(MethodUrlCompletion.NO)

                                        // optionals
                                        .WithCustomerAccountId("6dcb24f5-74a0-4da3-98da-4f0aa0e88db3")
                                        .WithAccountAgeIndicator(AgeIndicator.LESS_THAN_THIRTY_DAYS)
                                        .WithAccountCreateDate(DateTime.Parse("2019-01-10"))
                                        .WithAccountChangeDate(DateTime.Parse("2019-01-28"))
                                        .WithAccountChangeIndicator(AgeIndicator.THIS_TRANSACTION)
                                        .WithPasswordChangeDate(DateTime.Parse("2019-01-15"))
                                        .WithPasswordChangeIndicator(AgeIndicator.LESS_THAN_THIRTY_DAYS)
                                        .WithHomeNumber("44", "123456798")
                                        .WithWorkNumber("44", "1801555888")
                                        .WithPaymentAccountCreateDate(DateTime.Parse("2019-01-01"))
                                        .WithPaymentAccountAgeIndicator(AgeIndicator.LESS_THAN_THIRTY_DAYS)
                                        .WithPreviousSuspiciousActivity(false)
                                        .WithNumberOfPurchasesInLastSixMonths(3)
                                        .WithNumberOfTransactionsInLast24Hours(1)
                                        .WithNumberOfTransactionsInLastYear(5)
                                        .WithNumberOfAddCardAttemptsInLast24Hours(1)
                                        .WithShippingAddressCreateDate(DateTime.Parse("2019-01-28"))
                                        .WithShippingAddressUsageIndicator(AgeIndicator.THIS_TRANSACTION)

                                        .Execute();
                Assert.IsNotNull(initAuth);

                // get authentication data
                secureEcom = Secure3dService.GetAuthenticationData()
                             .WithServerTransactionId(initAuth.ServerTransactionId)
                             .Execute();
                card.ThreeDSecure = secureEcom;

                if (secureEcom.Status.Equals("AUTHENTICATION_SUCCESSFUL"))
                {
                    Transaction response = card.Charge(10.01m)
                                           .WithCurrency("USD")
                                           .Execute();
                    Assert.IsNotNull(response);
                    Assert.AreEqual("00", response.ResponseCode);
                }
                else
                {
                    Assert.Fail("Signature verification failed.");
                }
            }
            else
            {
                Assert.Fail("Card not enrolled.");
            }
        }
Ejemplo n.º 19
0
        public void OptionalOrderLevelFields()
        {
            // check enrollment
            ThreeDSecure secureEcom = Secure3dService.CheckEnrollment(card)
                                      .Execute(Secure3dVersion.Two);

            Assert.IsNotNull(secureEcom);

            if (secureEcom.Enrolled.Equals("True"))
            {
                Assert.AreEqual(Secure3dVersion.Two, secureEcom.Version);

                // initiate authentication
                ThreeDSecure initAuth = Secure3dService.InitiateAuthentication(card, secureEcom)
                                        .WithAmount(250m)
                                        .WithCurrency("USD")
                                        .WithOrderCreateDate(DateTime.Now)
                                        .WithAddress(billingAddress, AddressType.Billing)
                                        .WithAddress(shippingAddress, AddressType.Shipping)
                                        .WithBrowserData(browserData)
                                        .WithMethodUrlCompletion(MethodUrlCompletion.NO)

                                        // optionals
                                        .WithGiftCardCount(1)
                                        .WithGiftCardCurrency("USD")
                                        .WithGiftCardAmount(250m)
                                        .WithDeliveryEmail("*****@*****.**")
                                        .WithDeliveryTimeFrame(DeliveryTimeFrame.ELECTRONIC_DELIVERY)
                                        .WithShippingMethod(ShippingMethod.ANOTHER_VERIFIED_ADDRESS)
                                        .WithShippingNameMatchesCardHolderName(true)
                                        .WithPreOrderIndicator(PreOrderIndicator.FUTURE_AVAILABILITY)
                                        .WithPreOrderAvailabilityDate(DateTime.Parse("2019-04-18"))
                                        .WithReorderIndicator(ReorderIndicator.REORDER)
                                        .WithOrderTransactionType(OrderTransactionType.GOODS_SERVICE_PURCHASE)

                                        .Execute();
                Assert.IsNotNull(initAuth);

                // get authentication data
                secureEcom = Secure3dService.GetAuthenticationData()
                             .WithServerTransactionId(initAuth.ServerTransactionId)
                             .Execute();
                card.ThreeDSecure = secureEcom;

                if (secureEcom.Status.Equals("AUTHENTICATION_SUCCESSFUL"))
                {
                    Transaction response = card.Charge(10.01m)
                                           .WithCurrency("USD")
                                           .Execute();
                    Assert.IsNotNull(response);
                    Assert.AreEqual("00", response.ResponseCode);
                }
                else
                {
                    Assert.Fail("Signature verification failed.");
                }
            }
            else
            {
                Assert.Fail("Card not enrolled.");
            }
        }
Ejemplo n.º 20
0
        public IActionResult DatosAuth([FromQuery] Tarjeta detalles, [FromQuery] RespuestaVersion3DS2 responseACSVersion)
        {
            // Configuramos los datos de nuestro comercio. Los datos son proporcionados por el equipo de Addon Payments,
            // en caso de duda debe llamar al 914 353 028 e indicar su número de comercio o Merchant ID
            ServicesContainer.ConfigureService(new GatewayConfig
            {
                MerchantId               = "addonnettest",
                AccountId                = "3ds2",
                SharedSecret             = "secret",
                MethodNotificationUrl    = "https://dominio.com/notificacion3ds",
                ChallengeNotificationUrl = "https://dominio.com/notificacionAcs",
                MerchantContactUrl       = "https://www.dominio.com/about",
                Secure3dVersion          = Secure3dVersion.Two
            });

            ThreeDSecure threeDSecureData = null;

            try
            {
                threeDSecureData = Secure3dService.GetAuthenticationData()
                                   .WithServerTransactionId(responseACSVersion.serverTransactionId)
                                   .Execute();

                // Informamos al cliente
                RespuestaVersion3DS2 respuesta = new RespuestaVersion3DS2
                {
                    acsEndVersion          = threeDSecureData.AcsEndVersion,
                    acsStartVersion        = threeDSecureData.AcsStartVersion,
                    acsTransactionId       = threeDSecureData.AcsTransactionId,
                    algorithm              = threeDSecureData.Algorithm,
                    authenticationSource   = threeDSecureData.AuthenticationSource,
                    authenticationType     = threeDSecureData.AuthenticationType,
                    authenticationValue    = threeDSecureData.AuthenticationValue,
                    cardHolderResponseInfo = threeDSecureData.CardHolderResponseInfo,
                    cavv = threeDSecureData.Cavv,
                    challengeMandated            = threeDSecureData.ChallengeMandated,
                    criticalityIndicator         = threeDSecureData.CriticalityIndicator,
                    directoryServerEndVersion    = threeDSecureData.DirectoryServerEndVersion,
                    directoryServerStartVersion  = threeDSecureData.DirectoryServerStartVersion,
                    directoryServerTransactionId = threeDSecureData.DirectoryServerTransactionId,
                    eci                        = threeDSecureData.Eci,
                    enrolled                   = threeDSecureData.Enrolled,
                    issuerAcsUrl               = threeDSecureData.IssuerAcsUrl,
                    messageCategory            = threeDSecureData.MessageCategory,
                    messageExtensionId         = threeDSecureData.MessageExtensionId,
                    messageExtensionName       = threeDSecureData.MessageExtensionName,
                    messageVersion             = threeDSecureData.MessageVersion,
                    payerAuthenticationRequest = threeDSecureData.PayerAuthenticationRequest,
                    paymentDataSource          = threeDSecureData.PaymentDataSource,
                    paymentDataType            = threeDSecureData.PaymentDataType,
                    sdkInterface               = threeDSecureData.SdkInterface,
                    sdkUiType                  = threeDSecureData.SdkUiType,
                    serverTransactionId        = threeDSecureData.ServerTransactionId,
                    status                     = threeDSecureData.Status,
                    statusReason               = threeDSecureData.StatusReason,
                    xid                        = threeDSecureData.Xid
                };

                return(Ok(respuesta));
            }

            catch (ApiException exce)
            {
                return(BadRequest(exce));
                // TODO: agregue su control de excepciones aquí
            }
        }
Ejemplo n.º 21
0
 public RealEx3DAuthRequest(string secret, string merchantId, string account, string orderId, Amount amount, Card card, TssInfo tssInfo, ThreeDSecure threeDSecure, bool autoSettle, string custNum, string prodId, string varRef, Comments comments)
     : base(secret, merchantId, account, orderId, amount, card, tssInfo, autoSettle, custNum, prodId, varRef, comments)
 {
     Mpi = new Mpi(threeDSecure.Cavv, threeDSecure.Xid, threeDSecure.Eci);
 }
Ejemplo n.º 22
0
        public IActionResult AuthFinal([FromQuery] Tarjeta detalles, [FromQuery] RespuestaVersion3DS2 responseACSVersion)
        {
            // Configuramos los datos de nuestro comercio. Los datos son proporcionados por el equipo de Addon Payments,
            // en caso de duda debe llamar al 914 353 028 e indicar su número de comercio o Merchant ID
            ServicesContainer.ConfigureService(new GatewayConfig
            {
                MerchantId   = "addonnettest",
                AccountId    = "3ds2",
                SharedSecret = "secret",
                ServiceUrl   = "https://remote.sandbox.addonpayments.com/remote"
            });

            // Creamos el objeto de la tarjeta
            var card = new CreditCardData
            {
                Number         = detalles.cardNumber,
                ExpMonth       = detalles.month,
                ExpYear        = detalles.year,
                Cvn            = detalles.cvn,
                CardHolderName = detalles.cardholderName
            };

            // Añadimos la información obtenida de autenticación 3DS2
            var threeDSecureData = new ThreeDSecure()
            {
                AuthenticationValue          = responseACSVersion.authenticationValue,
                DirectoryServerTransactionId = responseACSVersion.directoryServerTransactionId,
                Eci            = responseACSVersion.eci,
                MessageVersion = responseACSVersion.messageVersion
            };

            // add the 3D Secure 2 data to the card object
            card.ThreeDSecure = threeDSecureData;

            Transaction response = null;

            try
            {
                response = card.Charge(10.01m)
                           .WithCurrency("EUR")
                           .Execute();


                // Obtenemos la respuesta y la mostramos
                var result              = response.ResponseCode;      // 00 == Success
                var message             = response.ResponseMessage;   // [ test system ] AUTHORISED
                var orderId             = response.OrderId;           // ezJDQjhENTZBLTdCNzNDQw
                var authCode            = response.AuthorizationCode; // 12345
                var paymentsReference   = response.TransactionId;     // pasref 14622680939731425
                var schemeReferenceData = response.SchemeId;          // MMC0F00YE4000000715

                // Devolvemos el resultado de la operación al cliente
                Respuesta respuesta = new Respuesta
                {
                    result              = result,
                    message             = message,
                    orderId             = orderId,
                    authCode            = authCode,
                    paymentsReference   = paymentsReference,
                    schemeReferenceData = schemeReferenceData
                };

                return(Ok(respuesta));
            }

            catch (ApiException exce)
            {
                return(BadRequest(exce));
            }
        }
Ejemplo n.º 23
0
 public RealEx3DAuthRequest RealEx3DAuthRequest(string orderId, Amount amount, Card card, ThreeDSecure threeDSecure, TssInfo tssInfo = null, string custNum = null, string prodId = null, string varRef = null, Comments comments = null)
 {
     return(new RealEx3DAuthRequest(secret, merchantId, account, orderId, amount, card, tssInfo, threeDSecure, true, custNum, prodId, varRef, comments));
 }
Ejemplo n.º 24
0
        public void FullCycle_Any()
        {
            ThreeDSecure secureEcom = Secure3dService.CheckEnrollment(card)
                                      .WithAmount(1m)
                                      .WithCurrency("USD")
                                      .Execute(Secure3dVersion.Any);

            Assert.IsNotNull(secureEcom);

            if (secureEcom.Enrolled.Equals("True"))
            {
                if (secureEcom.Version.Equals(Secure3dVersion.Two))
                {
                    // initiate authentication
                    ThreeDSecure initAuth = Secure3dService.InitiateAuthentication(card, secureEcom)
                                            .WithAmount(10.01m)
                                            .WithCurrency("USD")
                                            .WithOrderCreateDate(DateTime.Now)
                                            .WithAddress(billingAddress, AddressType.Billing)
                                            .WithAddress(shippingAddress, AddressType.Shipping)
                                            .WithBrowserData(browserData)
                                            .Execute();
                    Assert.IsNotNull(initAuth);

                    // get authentication data
                    secureEcom = Secure3dService.GetAuthenticationData()
                                 .WithServerTransactionId(initAuth.ServerTransactionId)
                                 .Execute();
                    card.ThreeDSecure = secureEcom;

                    if (secureEcom.Status.Equals("AUTHENTICATION_SUCCESSFUL"))
                    {
                        Transaction response = card.Charge(10.01m)
                                               .WithCurrency("USD")
                                               .Execute();
                        Assert.IsNotNull(response);
                        Assert.AreEqual("00", response.ResponseCode);
                    }
                    else
                    {
                        Assert.Fail("Signature verification Assert.Failed.");
                    }
                }
                else
                {
                    // authenticate
                    ThreeDSecureAcsClient authClient = new ThreeDSecureAcsClient(secureEcom.IssuerAcsUrl);
                    var authResponse = authClient.Authenticate(secureEcom.PayerAuthenticationRequest, secureEcom.MerchantData.ToString());

                    string payerAuthenticationResponse = authResponse.getAuthResponse();
                    MerchantDataCollection md          = MerchantDataCollection.Parse(authResponse.getMerchantData());

                    // verify signature through the service and affix to the card object
                    secureEcom = Secure3dService.GetAuthenticationData()
                                 .WithPayerAuthenticationResponse(payerAuthenticationResponse)
                                 .WithMerchantData(md)
                                 .Execute();
                    card.ThreeDSecure = secureEcom;

                    if (secureEcom.Status.Equals("Y"))
                    {
                        Transaction response = card.Charge().Execute();
                        Assert.IsNotNull(response);
                        Assert.AreEqual("00", response.ResponseCode);
                    }
                    else
                    {
                        Assert.Fail("Signature verification Assert.Failed.");
                    }
                }
            }
            else
            {
                Assert.Fail("Card not enrolled.");
            }
        }
Ejemplo n.º 25
0
 public static Secure3dBuilder InitiateAuthentication(IPaymentMethod paymentMethod, ThreeDSecure secureEcom)
 {
     if (paymentMethod is ISecure3d)
     {
         ((ISecure3d)paymentMethod).ThreeDSecure = secureEcom;
     }
     return(new Secure3dBuilder(TransactionType.InitiateAuthentication)
            .WithPaymentMethod(paymentMethod));
 }