Example #1
0
        public static TransactionSummary MapTransactionSummary(JsonDoc doc)
        {
            JsonDoc paymentMethod = doc.Get("payment_method");

            JsonDoc card = paymentMethod?.Get("card");

            var summary = new TransactionSummary {
                TransactionId         = doc.GetValue <string>("id"),
                TransactionDate       = doc.GetValue <DateTime?>("time_created", DateConverter),
                TransactionStatus     = doc.GetValue <string>("status"),
                TransactionType       = doc.GetValue <string>("type"),
                Channel               = doc.GetValue <string>("channel"),
                Amount                = doc.GetValue <string>("amount").ToAmount(),
                Currency              = doc.GetValue <string>("currency"),
                ReferenceNumber       = doc.GetValue <string>("reference"),
                ClientTransactionId   = doc.GetValue <string>("reference"),
                TransactionLocalDate  = doc.GetValue <DateTime?>("time_created_reference", DateConverter),
                BatchSequenceNumber   = doc.GetValue <string>("batch_id"),
                Country               = doc.GetValue <string>("country"),
                OriginalTransactionId = doc.GetValue <string>("parent_resource_id"),
                DepositReference      = doc.GetValue <string>("deposit_id"),
                DepositDate           = doc.GetValue <DateTime?>("deposit_time_created", DateConverter),

                GatewayResponseMessage = paymentMethod?.GetValue <string>("message"),
                EntryMode      = paymentMethod?.GetValue <string>("entry_mode"),
                CardHolderName = paymentMethod?.GetValue <string>("name"),

                CardType               = card?.GetValue <string>("brand"),
                AuthCode               = card?.GetValue <string>("authcode"),
                BrandReference         = card?.GetValue <string>("brand_reference"),
                AquirerReferenceNumber = card?.GetValue <string>("arn"),
                MaskedCardNumber       = card?.GetValue <string>("masked_number_first6last4"),

                MerchantId        = doc.Get("system")?.GetValue <string>("mid"),
                MerchantHierarchy = doc.Get("system")?.GetValue <string>("hierarchy"),
                MerchantName      = doc.Get("system")?.GetValue <string>("name"),
                MerchantDbaName   = doc.Get("system")?.GetValue <string>("dba"),
            };

            return(summary);
        }
Example #2
0
        public TransactionResponse(JsonDoc root)
        {
            var response = root.Get("data");

            if (response == null)
            {
                return;
            }

            RequestId = response.GetValue <string>("requestId");
            HydrateCmdResult(response);
            var responseData = response.Get("data");

            if (responseData == null)
            {
                return;
            }
            HydrateHostData(responseData);
            HydratePaymentData(responseData);
            HydrateEmvData(responseData);
        }
        public static Transaction MapResponse(string rawResponse)
        {
            Transaction transaction = new Transaction();

            if (!string.IsNullOrEmpty(rawResponse))
            {
                JsonDoc json = JsonDoc.Parse(rawResponse);

                transaction.TransactionId     = json.GetValue <string>("ob_trans_id");
                transaction.PaymentMethodType = PaymentMethodType.BankPayment;
                transaction.OrderId           = json.Get("order")?.GetValue <string>("id");
                transaction.ResponseMessage   = json.GetValue <string>("status");

                BankPaymentResponse obResponse = new BankPaymentResponse();
                obResponse.RedirectUrl          = json.GetValue <string>("redirect_url");
                obResponse.PaymentStatus        = json.GetValue <string>("status");
                obResponse.Id                   = json.GetValue <string>("ob_trans_id");
                transaction.BankPaymentResponse = obResponse;
            }

            return(transaction);
        }
Example #4
0
        public void MapTransactionSummaryTest_NullDates()
        {
            // Arrange
            string rawJson = "{\"id\":\"TRN_TvY1QFXxQKtaFSjNaLnDVdo3PZ7ivz\",\"time_created\":\"\",\"time_last_updated\":\"\",\"status\":\"PREAUTHORIZED\",\"type\":\"SALE\",\"merchant_id\":\"MER_c4c0df11039c48a9b63701adeaa296c3\",\"merchant_name\":\"Sandbox_merchant_2\",\"account_id\":\"TRA_6716058969854a48b33347043ff8225f\",\"account_name\":\"Transaction_Processing\",\"channel\":\"CNP\",\"amount\":\"10000\",\"currency\":\"CAD\",\"reference\":\"My-TRANS-184398775\",\"description\":\"41e7877b-da90-4c5f-befe-7f024b96311e\",\"order_reference\":\"\",\"time_created_reference\":\"\",\"batch_id\":\"\",\"initiator\":\"\",\"country\":\"\",\"language\":\"\",\"ip_address\":\"97.107.232.5\",\"site_reference\":\"\",\"payment_method\":{\"result\":\"00\",\"message\":\"SUCCESS\",\"entry_mode\":\"ECOM\",\"name\":\"NAME NOT PROVIDED\",\"card\":{\"funding\":\"CREDIT\",\"brand\":\"VISA\",\"authcode\":\"12345\",\"brand_reference\":\"TQ76bJf7qzkC30U0\",\"masked_number_first6last4\":\"411111XXXXXX1111\",\"cvv_indicator\":\"PRESENT\",\"cvv_result\":\"MATCHED\",\"avs_address_result\":\"MATCHED\",\"avs_postal_code_result\":\"MATCHED\"}},\"action_create_id\":\"ACT_TvY1QFXxQKtaFSjNaLnDVdo3PZ7ivz\",\"parent_resource_id\":\"TRN_TvY1QFXxQKtaFSjNaLnDVdo3PZ7ivz\",\"action\":{\"id\":\"ACT_kLkU0qND7wyuW0Br76ZNyAnlPTjHsb\",\"type\":\"TRANSACTION_SINGLE\",\"time_created\":\"\",\"result_code\":\"SUCCESS\",\"app_id\":\"JF2GQpeCrOivkBGsTRiqkpkdKp67Gxi0\",\"app_name\":\"test_app\"}}";

            JsonDoc doc = JsonDoc.Parse(rawJson);

            // Act
            TransactionSummary transaction = GpApiMapping.MapTransactionSummary(doc);

            // Assert
            Assert.AreEqual(doc.GetValue <string>("id"), transaction.TransactionId);
            Assert.IsNull(transaction.TransactionDate);
            Assert.AreEqual(doc.GetValue <string>("status"), transaction.TransactionStatus);
            Assert.AreEqual(doc.GetValue <string>("type"), transaction.TransactionType);
            Assert.AreEqual(doc.GetValue <string>("channel"), transaction.Channel);
            Assert.AreEqual(doc.GetValue <string>("amount").ToAmount(), transaction.Amount);
            Assert.AreEqual(doc.GetValue <string>("currency"), transaction.Currency);
            Assert.AreEqual(doc.GetValue <string>("reference"), transaction.ReferenceNumber);
            Assert.AreEqual(doc.GetValue <string>("reference"), transaction.ClientTransactionId);
            Assert.AreEqual(doc.GetValue <string>("batch_id"), transaction.BatchSequenceNumber);
            Assert.AreEqual(doc.GetValue <string>("country"), transaction.Country);
            Assert.AreEqual(doc.GetValue <string>("parent_resource_id"), transaction.OriginalTransactionId);

            var paymentMethod = doc.Get("payment_method");

            Assert.AreEqual(paymentMethod?.GetValue <string>("message"), transaction.GatewayResponseMessage);
            Assert.AreEqual(paymentMethod?.GetValue <string>("entry_mode"), transaction.EntryMode);
            Assert.AreEqual(paymentMethod?.GetValue <string>("name"), transaction.CardHolderName);

            var card = paymentMethod.Get("card");

            Assert.AreEqual(card?.GetValue <string>("brand"), transaction.CardType);
            Assert.AreEqual(card?.GetValue <string>("authcode"), transaction.AuthCode);
            Assert.AreEqual(card?.GetValue <string>("brand_reference"), transaction.BrandReference);
            Assert.AreEqual(card?.GetValue <string>("arn"), transaction.AquirerReferenceNumber);
            Assert.AreEqual(card?.GetValue <string>("masked_number_first6last4"), transaction.MaskedCardNumber);
        }
Example #5
0
        public static TransactionSummary MapTransactionSummary(JsonDoc doc)
        {
            JsonDoc paymentMethod = doc.Get("payment_method");

            JsonDoc card = paymentMethod?.Get("card");

            var summary = new TransactionSummary {
                //ToDo: Map all transaction properties
                TransactionId       = doc.GetValue <string>("id"),
                TransactionDate     = doc.GetValue <DateTime>("time_created"),
                TransactionStatus   = doc.GetValue <string>("status"),
                TransactionType     = doc.GetValue <string>("type"),
                Channel             = doc.GetValue <string>("channel"),
                Amount              = doc.GetValue <string>("amount").ToAmount(),
                Currency            = doc.GetValue <string>("currency"),
                ReferenceNumber     = doc.GetValue <string>("reference"),
                ClientTransactionId = doc.GetValue <string>("reference"),
                // ?? = doc.GetValue<DateTime>("time_created_reference"),
                BatchSequenceNumber = doc.GetValue <string>("batch_id"),
                Country             = doc.GetValue <string>("country"),
                // ?? = doc.GetValue<string>("action_create_id"),
                OriginalTransactionId = doc.GetValue <string>("parent_resource_id"),

                GatewayResponseMessage = paymentMethod?.GetValue <string>("message"),
                EntryMode      = paymentMethod?.GetValue <string>("entry_mode"),
                CardHolderName = paymentMethod?.GetValue <string>("name"),

                CardType               = card?.GetValue <string>("brand"),
                AuthCode               = card?.GetValue <string>("authcode"),
                BrandReference         = card?.GetValue <string>("brand_reference"),
                AquirerReferenceNumber = card?.GetValue <string>("arn"),
                MaskedCardNumber       = card?.GetValue <string>("masked_number_first6last4"),
            };

            return(summary);
        }
Example #6
0
        private Transaction MapResponse(string rawResponse)
        {
            Transaction transaction = new Transaction();

            if (!string.IsNullOrEmpty(rawResponse))
            {
                JsonDoc json = JsonDoc.Parse(rawResponse);

                // ToDo: Map transaction values
                transaction.TransactionId   = json.GetValue <string>("id");
                transaction.BalanceAmount   = json.GetValue <decimal>("amount");
                transaction.Timestamp       = json.GetValue <string>("time_created");
                transaction.ResponseMessage = json.GetValue <string>("status");
                transaction.ReferenceNumber = json.GetValue <string>("reference");
                transaction.BatchSummary    = new BatchSummary
                {
                    SequenceNumber = json.GetValue <string>("batch_id")
                };
                transaction.ResponseCode = json.Get("action").GetValue <string>("result_code");
                transaction.Token        = json.GetValue <string>("id");
            }

            return(transaction);
        }
Example #7
0
        public void MapResponseTest_CreateTransaction()
        {
            // Arrange
            string rawJson = "{\"id\":\"TRN_BHZ1whvNJnMvB6dPwf3znwWTsPjCn0\",\"time_created\":\"2020-12-04T12:46:05.235Z\",\"type\":\"SALE\",\"status\":\"PREAUTHORIZED\",\"channel\":\"CNP\",\"capture_mode\":\"LATER\",\"amount\":\"1400\",\"currency\":\"USD\",\"country\":\"US\",\"merchant_id\":\"MER_c4c0df11039c48a9b63701adeaa296c3\",\"merchant_name\":\"Sandbox_merchant_2\",\"account_id\":\"TRA_6716058969854a48b33347043ff8225f\",\"account_name\":\"Transaction_Processing\",\"reference\":\"15fbcdd9-8626-4e29-aae8-050f823f995f\",\"payment_method\":{\"id\":\"PMT_9a8f1b66-58e3-409d-86df-ed5fb14ad2f6\",\"result\":\"00\",\"message\":\"[ test system ] AUTHORISED\",\"entry_mode\":\"ECOM\",\"card\":{\"brand\":\"VISA\",\"masked_number_last4\":\"XXXXXXXXXXXX5262\",\"authcode\":\"12345\",\"brand_reference\":\"PSkAnccWLNMTcRmm\",\"brand_time_created\":\"\",\"cvv_result\":\"MATCHED\"}},\"batch_id\":\"\",\"action\":{\"id\":\"ACT_BHZ1whvNJnMvB6dPwf3znwWTsPjCn0\",\"type\":\"PREAUTHORIZE\",\"time_created\":\"2020-12-04T12:46:05.235Z\",\"result_code\":\"SUCCESS\",\"app_id\":\"Uyq6PzRbkorv2D4RQGlldEtunEeGNZll\",\"app_name\":\"sample_app_CERT\"}}";

            // Act
            Transaction transaction = GpApiMapping.MapResponse(rawJson);

            JsonDoc doc = JsonDoc.Parse(rawJson);

            // Assert
            Assert.AreEqual(doc.GetValue <string>("id"), transaction.TransactionId);
            Assert.AreEqual(doc.GetValue <string>("amount").ToAmount(), transaction.BalanceAmount);
            Assert.AreEqual(doc.GetValue <string>("time_created"), transaction.Timestamp);
            Assert.AreEqual(doc.GetValue <string>("status"), transaction.ResponseMessage);
            Assert.AreEqual(doc.GetValue <string>("reference"), transaction.ReferenceNumber);
            Assert.AreEqual(doc.GetValue <string>("batch_id"), transaction.BatchSummary?.BatchReference);
            Assert.AreEqual(doc.Get("action").GetValue <string>("result_code"), transaction.ResponseCode);
            Assert.AreEqual(doc.Get("payment_method")?.GetValue <string>("id"), transaction.Token);
            Assert.AreEqual(doc.Get("payment_method")?.GetValue <string>("result"), transaction.AuthorizationCode);
            Assert.AreEqual(doc.Get("payment_method")?.Get("card")?.GetValue <string>("brand"), transaction.CardType);
            Assert.AreEqual(doc.Get("payment_method")?.Get("card")?.GetValue <string>("masked_number_last4"), transaction.CardLast4);
            Assert.AreEqual(doc.Get("payment_method")?.Get("card")?.GetValue <string>("cvv_result"), transaction.CvnResponseMessage);
        }
Example #8
0
        public static Transaction MapResponse(string rawResponse)
        {
            Transaction transaction = new Transaction();

            if (!string.IsNullOrEmpty(rawResponse))
            {
                JsonDoc json = JsonDoc.Parse(rawResponse);

                transaction.ResponseCode    = json.Get("action")?.GetValue <string>("result_code");
                transaction.ResponseMessage = json.GetValue <string>("status");

                string actionType = json.Get("action")?.GetValue <string>("type");

                switch (actionType)
                {
                case BATCH_CLOSE:
                    transaction.BatchSummary = new BatchSummary {
                        BatchReference   = json.GetValue <string>("id"),
                        Status           = json.GetValue <string>("status"),
                        TotalAmount      = json.GetValue <string>("amount").ToAmount(),
                        TransactionCount = json.GetValue <int>("transaction_count"),
                    };
                    return(transaction);

                case PAYMENT_METHOD_CREATE:
                case PAYMENT_METHOD_DETOKENIZE:
                case PAYMENT_METHOD_EDIT:
                case PAYMENT_METHOD_DELETE:
                    transaction.Token           = json.GetValue <string>("id");
                    transaction.TokenUsageMode  = GetPaymentMethodUsageMode(json);
                    transaction.Timestamp       = json.GetValue <string>("time_created");
                    transaction.ReferenceNumber = json.GetValue <string>("reference");
                    transaction.CardType        = json.Get("card")?.GetValue <string>("brand");
                    transaction.CardNumber      = json.Get("card")?.GetValue <string>("number");
                    transaction.CardLast4       = json.Get("card")?.GetValue <string>("masked_number_last4");
                    transaction.CardExpMonth    = json.Get("card")?.GetValue <int>("expiry_month");
                    transaction.CardExpYear     = json.Get("card")?.GetValue <int>("expiry_year");
                    return(transaction);

                case LINK_CREATE:
                case LINK_EDIT:
                    transaction.PayLinkResponse = MapPayLinkResponse(json);
                    if (json.Has("transactions"))
                    {
                        var trn = json.Get("transactions");
                        transaction.BalanceAmount = trn.GetValue <string>("amount").ToAmount();
                        transaction.PayLinkResponse.AllowedPaymentMethods = GetAllowedPaymentMethods(trn);
                    }
                    return(transaction);

                default:
                    break;
                }

                transaction.TransactionId    = json.GetValue <string>("id");
                transaction.BalanceAmount    = json.GetValue <string>("amount").ToAmount();
                transaction.AuthorizedAmount = (json.GetValue <string>("status").ToUpper().Equals(TransactionStatus.Preauthorized.ToString().ToUpper()) && !string.IsNullOrEmpty(json.GetValue <string>("amount"))) ?
                                               json.GetValue <string>("amount").ToAmount() : null;
                transaction.Timestamp            = json.GetValue <string>("time_created");
                transaction.ResponseMessage      = json.GetValue <string>("status");
                transaction.ReferenceNumber      = json.GetValue <string>("reference");
                transaction.ClientTransactionId  = json.GetValue <string>("reference");
                transaction.FingerPrint          = json.Get("payment_method")?.GetValue <string>("fingerprint") ?? null;
                transaction.FingerPrintIndicator = json.Get("payment_method")?.GetValue <string>("fingerprint_presence_indicator") ?? null;
                transaction.BatchSummary         = new BatchSummary {
                    BatchReference = json.GetValue <string>("batch_id")
                };
                transaction.Token                  = json.Get("payment_method")?.GetValue <string>("id");
                transaction.AuthorizationCode      = json.Get("payment_method")?.GetValue <string>("result");
                transaction.CardType               = json.Get("payment_method")?.Get("card")?.GetValue <string>("brand");
                transaction.CardLast4              = json.Get("payment_method")?.Get("card")?.GetValue <string>("masked_number_last4");
                transaction.CvnResponseMessage     = json.Get("payment_method")?.Get("card")?.GetValue <string>("cvv_result");
                transaction.CardBrandTransactionId = json.Get("payment_method")?.Get("card")?.GetValue <string>("brand_reference");
                transaction.AvsResponseCode        = json.Get("payment_method")?.Get("card")?.GetValue <string>("avs_postal_code_result");
                transaction.AvsAddressResponse     = json.Get("payment_method")?.Get("card")?.GetValue <string>("avs_address_result");
                transaction.AvsResponseMessage     = json.Get("payment_method")?.Get("card")?.GetValue <string>("avs_action");
                transaction.MultiCapture           = GetIsMultiCapture(json);
                transaction.PaymentMethodType      = GetPaymentMehodType(json) ?? transaction.PaymentMethodType;
                transaction.DccRateData            = MapDccInfo(json);
            }

            return(transaction);
        }
Example #9
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);
        }
        public SafReportResponse(JsonDoc root)
        {
            var firstDataNode = root.Get("data");

            if (firstDataNode == null)
            {
                throw new MessageException(INVALID_RESPONSE_FORMAT);
            }

            var cmdResult = firstDataNode.Get("cmdResult");

            if (cmdResult == null)
            {
                throw new MessageException(INVALID_RESPONSE_FORMAT);
            }

            Status = cmdResult.GetValue <string>("result");
            if (string.IsNullOrEmpty(Status))
            {
                var errorCode = cmdResult.GetValue <string>("errorCode");
                var errorMsg  = cmdResult.GetValue <string>("errorMessage");
                DeviceResponseText = $"Error: {errorCode} - {errorMsg}";
            }
            else
            {
                // If the Status is not "Success", there is either nothing to process, or something else went wrong.
                // Skip the processing of the rest of the message, as we'll likely hit null reference exceptions
                if (Status == "Success")
                {
                    ReportResult = new SafReport();
                    var secondDataNode = firstDataNode.Get("data");
                    if (secondDataNode == null)
                    {
                        throw new MessageException(INVALID_RESPONSE_FORMAT);
                    }
                    Multiplemessage = secondDataNode.GetValue <string>("multipleMessage");
                    var safDetailsList = secondDataNode.GetEnumerator("SafDetails");

                    foreach (var detail in safDetailsList)
                    {
                        var safRecords = detail.GetEnumerator("SafRecords");

                        if (ReportResult.TotalAmount == null)
                        {
                            ReportResult.TotalAmount = 0.00m;
                        }

                        ReportResult.TotalAmount += detail.GetValue <decimal>("SafTotal");
                        ReportResult.TotalCount  += detail.GetValue <int>("SafCount");

                        SummaryResponse summaryResponse = new SummaryResponse()
                        {
                            TotalAmount  = detail.GetValue <decimal>("SafTotal"),
                            Count        = detail.GetValue <int>("SafCount"),
                            SummaryType  = MapSummaryType(detail.GetValue <string>("SafType")),
                            Transactions = new List <TransactionSummary>()
                        };

                        if (detail.Has("SafRecords"))
                        {
                            foreach (var record in detail.GetEnumerator("SafRecords"))
                            {
                                TransactionSummary transactionSummary = new TransactionSummary()
                                {
                                    TransactionType   = record.GetValue <string>("transactionType"),
                                    TerminalRefNumber = record.GetValue <string>("transId"), // The sample XML says tranNo?
                                    ReferenceNumber   = record.GetValue <string>("referenceNumber"),
                                    GratuityAmount    = record.GetValue <decimal>("tipAmount"),
                                    TaxAmount         = record.GetValue <decimal>("taxAmount"),
                                    Amount            = record.GetValue <decimal>("baseAmount"),
                                    AuthorizedAmount  = record.GetValue <decimal>("authorizedAmount"),
                                    //AmountDue = record.GetValue<decimal>("totalAmount"),
                                    CardType         = record.GetValue <string>("cardType"),
                                    MaskedCardNumber = record.GetValue <string>("maskedPan"),
                                    TransactionDate  = record.GetValue <DateTime>("transactionTime"),
                                    AuthCode         = record.GetValue <string>("approvalCode"),
                                    HostTimeout      = record.GetValue <bool>("hostTimeOut"),
                                    CardEntryMethod  = record.GetValue <string>("cardAcquisition"),
                                    Status           = record.GetValue <string>("responseCode"),
                                    //record.GetValue<decimal>("requestAmount")
                                };
                                summaryResponse.Transactions.Add(transactionSummary);
                            }
                        }

                        if (summaryResponse.SummaryType == SummaryType.Approved)
                        {
                            if (ReportResult.Approved == null)
                            {
                                ReportResult.Approved = new Dictionary <SummaryType, SummaryResponse>();
                            }
                            ReportResult.Approved.Add(summaryResponse.SummaryType, summaryResponse);
                        }
                        else if (summaryResponse.SummaryType == SummaryType.Pending)
                        {
                            if (ReportResult.Pending == null)
                            {
                                ReportResult.Pending = new Dictionary <SummaryType, SummaryResponse>();
                            }
                            ReportResult.Pending.Add(summaryResponse.SummaryType, summaryResponse);
                        }
                        else if (summaryResponse.SummaryType == SummaryType.Declined)
                        {
                            if (ReportResult.Declined == null)
                            {
                                ReportResult.Declined = new Dictionary <SummaryType, SummaryResponse>();
                            }
                            ReportResult.Declined.Add(summaryResponse.SummaryType, summaryResponse);
                        }
                    }
                }
                else   // the only other option is "Failed"
                {
                    var errorCode = cmdResult.GetValue <string>("errorCode");
                    var errorMsg  = cmdResult.GetValue <string>("errorMessage");
                    DeviceResponseText = $"Error: {errorCode} - {errorMsg}";
                }
            }
        }
Example #11
0
        private T MapReportResponse <T>(string rawResponse, ReportType reportType) where T : class
        {
            T result = Activator.CreateInstance <T>();

            JsonDoc json = JsonDoc.Parse(rawResponse);

            Func <object, decimal?> decimalConverter = (value) => {
                decimal amount;
                if (value is string && decimal.TryParse(value as string, out amount))
                {
                    return(amount);
                }
                return(null);
            };

            Func <JsonDoc, TransactionSummary> mapTransactionSummary = (doc) => {
                JsonDoc paymentMethod = doc.Get("payment_method");

                JsonDoc card = paymentMethod?.Get("card");

                var summary = new TransactionSummary {
                    //ToDo: Map all transaction properties
                    TransactionId       = doc.GetValue <string>("id"),
                    TransactionDate     = doc.GetValue <DateTime>("time_created"),
                    TransactionStatus   = doc.GetValue <string>("status"),
                    TransactionType     = doc.GetValue <string>("type"),
                    Channel             = doc.GetValue <string>("channel"),
                    Amount              = doc.GetValue("amount", decimalConverter),
                    Currency            = doc.GetValue <string>("currency"),
                    ReferenceNumber     = doc.GetValue <string>("reference"),
                    ClientTransactionId = doc.GetValue <string>("reference"),
                    // ?? = doc.GetValue<DateTime>("time_created_reference"),
                    BatchSequenceNumber = doc.GetValue <string>("batch_id"),
                    Country             = doc.GetValue <string>("country"),
                    // ?? = doc.GetValue<string>("action_create_id"),
                    OriginalTransactionId = doc.GetValue <string>("parent_resource_id"),

                    GatewayResponseMessage = paymentMethod?.GetValue <string>("message"),
                    EntryMode = paymentMethod?.GetValue <string>("entry_mode"),
                    //?? = paymentMethod?.GetValue<string>("name"),

                    CardType = card?.GetValue <string>("brand"),
                    AuthCode = card?.GetValue <string>("authcode"),
                    //?? = card?.GetValue<string>("brand_reference"),
                    AquirerReferenceNumber = card?.GetValue <string>("arn"),
                    MaskedCardNumber       = card?.GetValue <string>("masked_number_first6last4"),
                };

                return(summary);
            };

            if (reportType == ReportType.TransactionDetail && result is TransactionSummary)
            {
                result = mapTransactionSummary(json) as T;
            }
            else if (reportType == ReportType.FindTransactions && result is IEnumerable <TransactionSummary> )
            {
                List <JsonDoc> transactions = json.GetValue <List <JsonDoc> >("transactions");
                foreach (var doc in transactions)
                {
                    (result as List <TransactionSummary>).Add(mapTransactionSummary(doc));
                }
            }

            return(result);
        }
        private static JsonDoc setOrderInformation(AuthorizationBuilder builder, ref JsonDoc requestBody)
        {
            JsonDoc order;

            if (requestBody.Has("order"))
            {
                order = requestBody.Get("order");
            }
            else
            {
                order = new JsonDoc();
            }
            order.Set("description", builder.OrderDetails?.Description);

            if (builder.ShippingAddress != null)
            {
                var shippingAddress = new JsonDoc()
                                      .Set("line1", builder.ShippingAddress.StreetAddress1)
                                      .Set("line2", builder.ShippingAddress.StreetAddress2)
                                      .Set("line3", builder.ShippingAddress.StreetAddress3)
                                      .Set("city", builder.ShippingAddress.City)
                                      .Set("postal_code", builder.ShippingAddress.PostalCode)
                                      .Set("state", builder.ShippingAddress.State)
                                      .Set("country", builder.ShippingAddress.CountryCode);

                order.Set("shipping_address", shippingAddress);
            }

            var shippingPhone = new JsonDoc()
                                .Set("country_code", builder.ShippingPhone?.CountryCode)
                                .Set("subscriber_number", builder.ShippingPhone?.Number);

            order.Set("shipping_phone", shippingPhone);

            decimal taxTotalAmount = 0;
            decimal itemsAmount    = 0;
            decimal?orderAmount    = null;

            if (builder.MiscProductData != null)
            {
                var items = new List <Dictionary <string, object> >();
                foreach (var product in builder.MiscProductData)
                {
                    var qta        = product.Quantity ?? 0;
                    var taxAmount  = product.TaxAmount ?? 0;
                    var unitAmount = product.UnitPrice ?? 0;
                    var item       = new Dictionary <string, object>();
                    item.Add("reference", product.ProductId);
                    item.Add("label", product.ProductName);
                    item.Add("description", product.Description);
                    item.Add("quantity", qta);
                    item.Add("unit_amount", unitAmount.ToNumericCurrencyString());
                    item.Add("unit_currency", product.UnitCurrency);
                    item.Add("tax_amount", taxAmount.ToNumericCurrencyString());
                    item.Add("amount", (qta * unitAmount).ToNumericCurrencyString());
                    items.Add(item);
                    taxTotalAmount += taxAmount;
                    itemsAmount    += unitAmount;
                }

                order.Set("tax_amount", taxTotalAmount.ToNumericCurrencyString());
                order.Set("item_amount", itemsAmount.ToNumericCurrencyString());
                var shippingAmount = builder.ShippingAmt ?? 0;
                order.Set("shipping_amount", builder.ShippingAmt.ToNumericCurrencyString());
                order.Set("insurance_offered", builder.OrderDetails != null ? (builder.OrderDetails.HasInsurance ? "YES" : "NO") : null);
                order.Set("shipping_discount", builder.ShippingDiscount?.ToNumericCurrencyString());
                order.Set("insurance_amount", builder.OrderDetails?.InsuranceAmount?.ToNumericCurrencyString());
                order.Set("handling_amount", builder.OrderDetails?.HandlingAmount?.ToNumericCurrencyString());
                var insuranceAmount = builder.OrderDetails?.InsuranceAmount ?? 0;
                var handlingAmount  = builder.OrderDetails?.HandlingAmount ?? 0;
                orderAmount = itemsAmount + taxTotalAmount + handlingAmount + insuranceAmount + shippingAmount;
                order.Set("amount", orderAmount.ToNumericCurrencyString());
                order.Set("currency", builder.Currency);
                order.Set("items", items);
            }
            if (!requestBody.Has("order"))
            {
                requestBody.Set("order", order);
            }

            return(requestBody);
        }
Example #13
0
        public void MapDepositSummaryTest_NullDates()
        {
            // Arrange
            string rawJson = "{\"id\":\"DEP_2342423423\",\"time_created\":\"\",\"status\":\"FUNDED\",\"funding_type\":\"CREDIT\",\"amount\":\"11400\",\"currency\":\"USD\",\"aggregation_model\":\"H-By Date\",\"bank_transfer\":{\"masked_account_number_last4\":\"XXXXXX9999\",\"bank\":{\"code\":\"XXXXX0001\"}},\"system\":{\"mid\":\"101023947262\",\"hierarchy\":\"055-70-024-011-019\",\"name\":\"XYZ LTD.\",\"dba\":\"XYZ Group\"},\"sales\":{\"count\":4,\"amount\":\"12400\"},\"refunds\":{\"count\":1,\"amount\":\"-1000\"},\"discounts\":{\"count\":0,\"amount\":\"\"},\"tax\":{\"count\":0,\"amount\":\"\"},\"disputes\":{\"chargebacks\":{\"count\":0,\"amount\":\"\"},\"reversals\":{\"count\":0,\"amount\":\"\"}},\"fees\":{\"amount\":\"\"},\"action\":{\"id\":\"ACT_TWdmMMOBZ91iQX1DcvxYermuVJ6E6h\",\"type\":\"DEPOSIT_SINGLE\",\"time_created\":\"\",\"result_code\":\"SUCCESS\",\"app_id\":\"JF2GQpeCrOivkBGsTRiqkpkdKp67Gxi0\",\"app_name\":\"test_app\"}}";

            JsonDoc doc = JsonDoc.Parse(rawJson);

            // Act
            DepositSummary deposit = GpApiMapping.MapDepositSummary(doc);

            // Assert
            Assert.AreEqual(doc.GetValue <string>("id"), deposit.DepositId);
            Assert.IsNull(deposit.DepositDate);
            Assert.AreEqual(doc.GetValue <string>("status"), deposit.Status);
            Assert.AreEqual(doc.GetValue <string>("funding_type"), deposit.Type);
            Assert.AreEqual(doc.GetValue <string>("amount").ToAmount(), deposit.Amount);
            Assert.AreEqual(doc.GetValue <string>("currency"), deposit.Currency);

            Assert.AreEqual(doc.Get("system")?.GetValue <string>("mid"), deposit.MerchantNumber);
            Assert.AreEqual(doc.Get("system")?.GetValue <string>("hierarchy"), deposit.MerchantHierarchy);
            Assert.AreEqual(doc.Get("system")?.GetValue <string>("name"), deposit.MerchantName);
            Assert.AreEqual(doc.Get("system")?.GetValue <string>("dba"), deposit.MerchantDbaName);

            Assert.AreEqual(doc.Get("sales")?.GetValue <int>("count") ?? default(int), deposit.SalesTotalCount);
            Assert.AreEqual(doc.Get("sales")?.GetValue <string>("amount").ToAmount(), deposit.SalesTotalAmount);

            Assert.AreEqual(doc.Get("refunds")?.GetValue <int>("count") ?? default(int), deposit.RefundsTotalCount);
            Assert.AreEqual(doc.Get("refunds")?.GetValue <string>("amount").ToAmount(), deposit.RefundsTotalAmount);

            Assert.AreEqual(doc.Get("disputes")?.Get("chargebacks")?.GetValue <int>("count") ?? default(int), deposit.ChargebackTotalCount);
            Assert.AreEqual(doc.Get("disputes")?.Get("chargebacks")?.GetValue <string>("amount").ToAmount(), deposit.ChargebackTotalAmount);

            Assert.AreEqual(doc.Get("disputes")?.Get("reversals")?.GetValue <int>("count") ?? default(int), deposit.AdjustmentTotalCount);
            Assert.AreEqual(doc.Get("disputes")?.Get("reversals")?.GetValue <string>("amount").ToAmount(), deposit.AdjustmentTotalAmount);

            Assert.AreEqual(doc.Get("fees")?.GetValue <string>("amount").ToAmount(), deposit.FeesTotalAmount);
        }
Example #14
0
        public static DepositSummary MapDepositSummary(JsonDoc doc)
        {
            var summary = new DepositSummary {
                DepositId   = doc.GetValue <string>("id"),
                DepositDate = doc.GetValue <DateTime>("time_created"),
                Status      = doc.GetValue <string>("status"),
                Type        = doc.GetValue <string>("funding_type"),
                Amount      = doc.GetValue <string>("amount").ToAmount(),
                Currency    = doc.GetValue <string>("currency"),

                MerchantNumber    = doc.Get("system")?.GetValue <string>("mid"),
                MerchantHierarchy = doc.Get("system")?.GetValue <string>("hierarchy"),
                MerchantName      = doc.Get("system")?.GetValue <string>("name"),
                MerchantDbaName   = doc.Get("system")?.GetValue <string>("dba"),

                SalesTotalCount  = doc.Get("sales")?.GetValue <int>("count") ?? default(int),
                SalesTotalAmount = doc.Get("sales")?.GetValue <string>("amount").ToAmount(),

                RefundsTotalCount  = doc.Get("refunds")?.GetValue <int>("count") ?? default(int),
                RefundsTotalAmount = doc.Get("refunds")?.GetValue <string>("amount").ToAmount(),

                ChargebackTotalCount  = doc.Get("disputes")?.Get("chargebacks")?.GetValue <int>("count") ?? default(int),
                ChargebackTotalAmount = doc.Get("disputes")?.Get("chargebacks")?.GetValue <string>("amount").ToAmount(),

                AdjustmentTotalCount  = doc.Get("disputes")?.Get("reversals")?.GetValue <int>("count") ?? default(int),
                AdjustmentTotalAmount = doc.Get("disputes")?.Get("reversals")?.GetValue <string>("amount").ToAmount(),

                FeesTotalAmount = doc.Get("fees")?.GetValue <string>("amount").ToAmount(),
            };

            return(summary);
        }
Example #15
0
        internal static GpApiRequest BuildRequest(AuthorizationBuilder builder, GpApiConnector gateway)
        {
            var paymentMethod = new JsonDoc()
                                .Set("entry_mode", GetEntryMode(builder)); // [MOTO, ECOM, IN_APP, CHIP, SWIPE, MANUAL, CONTACTLESS_CHIP, CONTACTLESS_SWIPE]

            if (builder.PaymentMethod is ICardData)
            {
                var cardData = builder.PaymentMethod as ICardData;

                var card = new JsonDoc()
                           .Set("number", cardData.Number)
                           .Set("expiry_month", cardData.ExpMonth.HasValue ? cardData.ExpMonth.ToString().PadLeft(2, '0') : null)
                           .Set("expiry_year", cardData.ExpYear.HasValue ? cardData.ExpYear.ToString().PadLeft(4, '0').Substring(2, 2) : null)
                           //.Set("track", "")
                           .Set("tag", builder.TagData)
                           .Set("cvv", cardData.Cvn)
                           .Set("cvv_indicator", EnumConverter.GetMapping(Target.GP_API, cardData.CvnPresenceIndicator)) // [ILLEGIBLE, NOT_PRESENT, PRESENT]
                           .Set("avs_address", builder.BillingAddress?.StreetAddress1)
                           .Set("avs_postal_code", builder.BillingAddress?.PostalCode)
                           .Set("funding", builder.PaymentMethod?.PaymentMethodType == PaymentMethodType.Debit ? "DEBIT" : "CREDIT") // [DEBIT, CREDIT]
                           .Set("authcode", builder.OfflineAuthCode);
                //.Set("brand_reference", "")

                card.Set("chip_condition", EnumConverter.GetMapping(Target.GP_API, builder.EmvChipCondition)); // [PREV_SUCCESS, PREV_FAILED]

                paymentMethod.Set("card", card);

                var tokenizationData = new JsonDoc()
                                       .Set("account_name", gateway.TokenizationAccountName)
                                       .Set("reference", builder.ClientTransactionId ?? Guid.NewGuid().ToString())
                                       .Set("usage_mode", EnumConverter.GetMapping(Target.GP_API, builder.TokenUsageMode))
                                       .Set("name", "")
                                       .Set("card", card);

                if (builder.TransactionType == TransactionType.Tokenize)
                {
                    return(new GpApiRequest {
                        Verb = HttpMethod.Post,
                        Endpoint = "/payment-methods",
                        RequestBody = tokenizationData.ToString(),
                    });
                }
                else if (builder.TransactionType == TransactionType.Verify)
                {
                    if (builder.RequestMultiUseToken && string.IsNullOrEmpty((builder.PaymentMethod as ITokenizable).Token))
                    {
                        return(new GpApiRequest {
                            Verb = HttpMethod.Post,
                            Endpoint = "/payment-methods",
                            RequestBody = tokenizationData.ToString(),
                        });
                    }
                    else
                    {
                        var verificationData = new JsonDoc()
                                               .Set("account_name", gateway.TransactionProcessingAccountName)
                                               .Set("channel", EnumConverter.GetMapping(Target.GP_API, gateway.Channel))
                                               .Set("reference", builder.ClientTransactionId ?? Guid.NewGuid().ToString())
                                               .Set("currency", builder.Currency)
                                               .Set("country", gateway.Country)
                                               .Set("payment_method", paymentMethod);

                        if (builder.PaymentMethod is ITokenizable && !string.IsNullOrEmpty((builder.PaymentMethod as ITokenizable).Token))
                        {
                            verificationData.Remove("payment_method");
                            verificationData.Set("payment_method", new JsonDoc()
                                                 .Set("entry_mode", GetEntryMode(builder))
                                                 .Set("id", (builder.PaymentMethod as ITokenizable).Token)
                                                 );
                        }

                        return(new GpApiRequest {
                            Verb = HttpMethod.Post,
                            Endpoint = "/verifications",
                            RequestBody = verificationData.ToString(),
                        });
                    }
                }
            }
            else if (builder.PaymentMethod is ITrackData)
            {
                var track = builder.PaymentMethod as ITrackData;

                var card = new JsonDoc()
                           .Set("track", track.Value)
                           .Set("tag", builder.TagData)
                           .Set("avs_address", builder.BillingAddress?.StreetAddress1)
                           .Set("avs_postal_code", builder.BillingAddress?.PostalCode)
                           .Set("authcode", builder.OfflineAuthCode);

                if (builder.TransactionType == TransactionType.Verify)
                {
                    paymentMethod.Set("card", card);

                    var verificationData = new JsonDoc()
                                           .Set("account_name", gateway.TransactionProcessingAccountName)
                                           .Set("channel", EnumConverter.GetMapping(Target.GP_API, gateway.Channel))
                                           .Set("reference", builder.ClientTransactionId ?? Guid.NewGuid().ToString())
                                           .Set("currency", builder.Currency)
                                           .Set("country", gateway.Country)
                                           .Set("payment_method", paymentMethod);

                    return(new GpApiRequest {
                        Verb = HttpMethod.Post,
                        Endpoint = "/verifications",
                        RequestBody = verificationData.ToString(),
                    });
                }

                if (builder.TransactionType == TransactionType.Sale || builder.TransactionType == TransactionType.Refund)
                {
                    if (string.IsNullOrEmpty(track.Value))
                    {
                        card.Set("number", track.Pan);
                        card.Set("expiry_month", track.Expiry?.Substring(2, 2));
                        card.Set("expiry_year", track.Expiry?.Substring(0, 2));
                    }
                    if (string.IsNullOrEmpty(builder.TagData))
                    {
                        card.Set("chip_condition", EnumConverter.GetMapping(Target.GP_API, builder.EmvChipCondition)); // [PREV_SUCCESS, PREV_FAILED]
                    }
                }

                if (builder.TransactionType == TransactionType.Sale)
                {
                    card.Set("funding", builder.PaymentMethod?.PaymentMethodType == PaymentMethodType.Debit ? "DEBIT" : "CREDIT"); // [DEBIT, CREDIT]
                }

                paymentMethod.Set("card", card);
            }

            // payment method storage mode
            if (builder.RequestMultiUseToken)
            {
                //ToDo: there might be a typo: should be storage_mode
                paymentMethod.Set("storage_model", "ON_SUCCESS");
            }

            // tokenized payment method
            if (builder.PaymentMethod is ITokenizable)
            {
                string token = ((ITokenizable)builder.PaymentMethod).Token;
                if (!string.IsNullOrEmpty(token))
                {
                    paymentMethod.Set("id", token);
                }
            }

            // pin block
            if (builder.PaymentMethod is IPinProtected)
            {
                paymentMethod.Get("card")?.Set("pin_block", ((IPinProtected)builder.PaymentMethod).PinBlock);
            }

            // authentication
            if (builder.PaymentMethod is CreditCardData)
            {
                paymentMethod.Set("name", (builder.PaymentMethod as CreditCardData).CardHolderName);

                var secureEcom = (builder.PaymentMethod as CreditCardData).ThreeDSecure;
                if (secureEcom != null)
                {
                    var three_ds = new JsonDoc()
                                   // Indicates the version of 3DS
                                   .Set("message_version", secureEcom.MessageVersion)
                                   // An indication of the degree of the authentication and liability shift obtained for this transaction.
                                   // It is determined during the 3D Secure process.
                                   .Set("eci", secureEcom.Eci)
                                   // The authentication value created as part of the 3D Secure process.
                                   .Set("value", secureEcom.AuthenticationValue)
                                   // The reference created by the 3DSecure provider to identify the specific authentication attempt.
                                   .Set("server_trans_ref", secureEcom.ServerTransactionId)
                                   // The reference created by the 3DSecure Directory Server to identify the specific authentication attempt.
                                   .Set("ds_trans_ref", secureEcom.DirectoryServerTransactionId);

                    var authentication = new JsonDoc().Set("three_ds", three_ds);

                    paymentMethod.Set("authentication", authentication);
                }
            }

            // encryption
            if (builder.PaymentMethod is IEncryptable)
            {
                var encryptionData = ((IEncryptable)builder.PaymentMethod).EncryptionData;

                if (encryptionData != null)
                {
                    var encryption = new JsonDoc()
                                     .Set("version", encryptionData.Version);

                    if (!string.IsNullOrEmpty(encryptionData.KTB))
                    {
                        encryption.Set("method", "KTB");
                        encryption.Set("info", encryptionData.KTB);
                    }
                    else if (!string.IsNullOrEmpty(encryptionData.KSN))
                    {
                        encryption.Set("method", "KSN");
                        encryption.Set("info", encryptionData.KSN);
                    }

                    if (encryption.Has("info"))
                    {
                        paymentMethod.Set("encryption", encryption);
                    }
                }
            }

            var data = new JsonDoc()
                       .Set("account_name", gateway.TransactionProcessingAccountName)
                       .Set("type", builder.TransactionType == TransactionType.Refund ? "REFUND" : "SALE") // [SALE, REFUND]
                       .Set("channel", EnumConverter.GetMapping(Target.GP_API, gateway.Channel))           // [CP, CNP]
                       .Set("capture_mode", GetCaptureMode(builder))                                       // [AUTO, LATER, MULTIPLE]
                                                                                                           //.Set("remaining_capture_count", "") //Pending Russell
                       .Set("authorization_mode", builder.AllowPartialAuth ? "PARTIAL" : null)
                       .Set("amount", builder.Amount.ToNumericCurrencyString())
                       .Set("currency", builder.Currency)
                       .Set("reference", builder.ClientTransactionId ?? Guid.NewGuid().ToString())
                       .Set("description", builder.Description)
                       //.Set("order_reference", builder.OrderId)
                       .Set("gratuity_amount", builder.Gratuity.ToNumericCurrencyString())
                       .Set("cashback_amount", builder.CashBackAmount.ToNumericCurrencyString())
                       .Set("surcharge_amount", builder.SurchargeAmount.ToNumericCurrencyString())
                       .Set("convenience_amount", builder.ConvenienceAmount.ToNumericCurrencyString())
                       .Set("country", gateway.Country)
                       //.Set("language", EnumConverter.GetMapping(Target.GP_API, Language))
                       .Set("ip_address", builder.CustomerIpAddress)
                       //.Set("site_reference", "") //
                       .Set("payment_method", paymentMethod);

            // set order reference
            if (!string.IsNullOrEmpty(builder.OrderId))
            {
                var order = new JsonDoc()
                            .Set("reference", builder.OrderId);

                data.Set("order", order);
            }

            // stored credential
            if (builder.StoredCredential != null)
            {
                data.Set("initiator", EnumConverter.GetMapping(Target.GP_API, builder.StoredCredential.Initiator));
                var storedCredential = new JsonDoc()
                                       .Set("model", EnumConverter.GetMapping(Target.GP_API, builder.StoredCredential.Type))
                                       .Set("reason", EnumConverter.GetMapping(Target.GP_API, builder.StoredCredential.Reason))
                                       .Set("sequence", EnumConverter.GetMapping(Target.GP_API, builder.StoredCredential.Sequence));
                data.Set("stored_credential", storedCredential);
            }

            return(new GpApiRequest {
                Verb = HttpMethod.Post,
                Endpoint = "/transactions",
                RequestBody = data.ToString(),
            });
        }
Example #16
0
        public BatchReportResponse(JsonDoc root)
        {
            var firstDataNode = root.Get("data");

            if (firstDataNode == null)
            {
                throw new MessageException(INVALID_RESPONSE_FORMAT);
            }

            var cmdResult = firstDataNode.Get("cmdResult");

            if (cmdResult == null)
            {
                throw new MessageException(INVALID_RESPONSE_FORMAT);
            }

            Status = cmdResult.GetValue <string>("result");
            if (string.IsNullOrEmpty(Status))
            {
                var errorCode = cmdResult.GetValue <string>("errorCode");
                var errorMsg  = cmdResult.GetValue <string>("errorMessage");
                DeviceResponseText = $"Error: {errorCode} - {errorMsg}";
            }
            else
            {
                // If the Status is not "Success", there is either nothing to process, or something else went wrong.
                // Skip the processing of the rest of the message, as we'll likely hit null reference exceptions
                if (Status == "Success")
                {
                    var secondDataNode = firstDataNode.Get("data");
                    if (secondDataNode == null)
                    {
                        throw new MessageException(INVALID_RESPONSE_FORMAT);
                    }

                    MerchantName    = secondDataNode.GetValue <string>("merchantName");
                    Multiplemessage = secondDataNode.GetValue <string>("multipleMessage");

                    var batchRecord = secondDataNode.Get("batchRecord");
                    if (batchRecord != null)
                    {
                        BatchRecord = new BatchRecordResponse()
                        {
                            BatchId           = batchRecord.GetValue <int>("batchId"),
                            BatchSeqNbr       = batchRecord.GetValue <int>("batchSeqNbr"),
                            BatchStatus       = batchRecord.GetValue <string>("batchStatus"),
                            OpenUtcDateTime   = batchRecord.GetValue <string>("openUtcDateTime"),
                            CloseUtcDateTime  = batchRecord.GetValue <string>("closeUtcDateTime"),
                            OpenTnxId         = batchRecord.GetValue <string>("openTnxId"),
                            TotalAmount       = batchRecord.GetValue <decimal>("totalAmount"),
                            TotalCnt          = batchRecord.GetValue <int>("totalCnt"),
                            CreditCnt         = batchRecord.GetValue <int>("credictCnt"),
                            CreditAmt         = batchRecord.GetValue <decimal>("creditAmt"),
                            DebitCnt          = batchRecord.GetValue <int>("debitCnt"),
                            DebitAmt          = batchRecord.GetValue <decimal>("debitAmt"),
                            SaleCnt           = batchRecord.GetValue <int>("saleCnt"),
                            SaleAmt           = batchRecord.GetValue <decimal>("saleAmt"),
                            ReturnCnt         = batchRecord.GetValue <int>("returnCnt"),
                            ReturnAmt         = batchRecord.GetValue <decimal>("returnAmt"),
                            TotalGratuityAmt  = batchRecord.GetValue <decimal>("totalGratuityAmt"),
                            BatchTransactions = new List <BatchTransactionResponse>()
                        };

                        foreach (var transaction in batchRecord.GetEnumerator("batchTransactions"))
                        {
                            var batchTransaction = new BatchTransactionResponse();
                            batchTransaction.CardType         = transaction.GetValue <string>("cardType");
                            batchTransaction.TotalAmount      = transaction.GetValue <decimal>("totalAmount");
                            batchTransaction.TotalCnt         = transaction.GetValue <int>("totalCnt");
                            batchTransaction.CreditCnt        = transaction.GetValue <int>("creditCnt");
                            batchTransaction.CreditAmt        = transaction.GetValue <decimal>("creditAmt");
                            batchTransaction.DebitCnt         = transaction.GetValue <int>("debitCnt");
                            batchTransaction.DebitAmt         = transaction.GetValue <decimal>("debitAmt");
                            batchTransaction.SaleCnt          = transaction.GetValue <int>("saleCnt");
                            batchTransaction.SaleAmt          = transaction.GetValue <decimal>("saleAmt");
                            batchTransaction.ReturnCnt        = transaction.GetValue <int>("returnCnt");
                            batchTransaction.ReturnAmt        = transaction.GetValue <decimal>("returnAmt");
                            batchTransaction.TotalGratuityAmt = transaction.GetValue <decimal>("totalGratuityAmt");
                            BatchRecord.BatchTransactions.Add(batchTransaction);
                        }
                    }
                }
                else   // the only other option is "Failed"
                {
                    var errorCode = cmdResult.GetValue <string>("errorCode");
                    var errorMsg  = cmdResult.GetValue <string>("errorMessage");
                    DeviceResponseText = $"Error: {errorCode} - {errorMsg}";
                }
            }
        }
Example #17
0
        public static Transaction Map3DSecureData(string rawResponse)
        {
            if (!string.IsNullOrEmpty(rawResponse))
            {
                JsonDoc json = JsonDoc.Parse(rawResponse);

                return(new Transaction {
                    ThreeDSecure = new ThreeDSecure {
                        ServerTransactionId = json.GetValue <string>("id"),
                        Status = json.GetValue <string>("status"),
                        Currency = json.GetValue <string>("currency"),
                        Amount = json.GetValue <string>("amount").ToAmount(),

                        Version = Parse3DSVersion(json.Get("three_ds")?.GetValue <string>("message_version")),
                        MessageVersion = json.Get("three_ds")?.GetValue <string>("message_version"),
                        DirectoryServerStartVersion = json.Get("three_ds")?.GetValue <string>("ds_protocol_version_start"),
                        DirectoryServerEndVersion = json.Get("three_ds")?.GetValue <string>("ds_protocol_version_end"),
                        DirectoryServerTransactionId = json.Get("three_ds")?.GetValue <string>("ds_trans_ref"),
                        AcsStartVersion = json.Get("three_ds")?.GetValue <string>("acs_protocol_version_start"),
                        AcsEndVersion = json.Get("three_ds")?.GetValue <string>("acs_protocol_version_end"),
                        AcsTransactionId = json.Get("three_ds")?.GetValue <string>("acs_trans_ref"),
                        Enrolled = json.Get("three_ds")?.GetValue <string>("enrolled_status"),
                        Eci = json.Get("three_ds")?.GetValue <string>("eci")?.ToInt32(),
                        AuthenticationValue = json.Get("three_ds")?.GetValue <string>("authentication_value"),
                        ChallengeMandated = json.Get("three_ds")?.GetValue <string>("challenge_status") == "MANDATED",
                        IssuerAcsUrl = !string.IsNullOrEmpty(json.Get("three_ds")?.GetValue <string>("method_url")) ?
                                       json.Get("three_ds")?.GetValue <string>("method_url") :
                                       json.Get("three_ds")?.GetValue <string>("acs_challenge_request_url"),
                        ChallengeReturnUrl = json.Get("notifications")?.GetValue <string>("challenge_return_url"),
                        SessionDataFieldName = json.Get("three_ds")?.GetValue <string>("session_data_field_name"),
                        MessageType = json.Get("three_ds")?.GetValue <string>("message_type"),
                        PayerAuthenticationRequest = (!string.IsNullOrEmpty(json.Get("three_ds")?.Get("method_data")?.GetValue <string>("encoded_method_data"))) ?
                                                     json.Get("three_ds")?.Get("method_data")?.GetValue <string>("encoded_method_data") :
                                                     json.Get("three_ds")?.GetValue <string>("challenge_value"),
                        StatusReason = json.Get("three_ds")?.GetValue <string>("status_reason"),
                        MessageCategory = json.Get("three_ds")?.GetValue <string>("message_category"),
                    }
                });
            }
            return(new Transaction());
        }
Example #18
0
        public static Transaction MapResponse(string rawResponse)
        {
            Transaction transaction = new Transaction();

            if (!string.IsNullOrEmpty(rawResponse))
            {
                JsonDoc json = JsonDoc.Parse(rawResponse);

                transaction.ResponseCode = json.Get("action")?.GetValue <string>("result_code");

                string actionType = json.Get("action")?.GetValue <string>("type");

                switch (actionType)
                {
                case BATCH_CLOSE:
                    transaction.BatchSummary = new BatchSummary {
                        BatchReference   = json.GetValue <string>("id"),
                        Status           = json.GetValue <string>("status"),
                        TotalAmount      = json.GetValue <string>("amount").ToAmount(),
                        TransactionCount = json.GetValue <int>("transaction_count"),
                    };
                    return(transaction);

                case PAYMENT_METHOD_CREATE:
                case PAYMENT_METHOD_DETOKENIZE:
                case PAYMENT_METHOD_EDIT:
                case PAYMENT_METHOD_DELETE:
                    transaction.Token           = json.GetValue <string>("id");
                    transaction.Timestamp       = json.GetValue <string>("time_created");
                    transaction.ReferenceNumber = json.GetValue <string>("reference");
                    transaction.CardType        = json.Get("card")?.GetValue <string>("brand");
                    transaction.CardNumber      = json.Get("card")?.GetValue <string>("number");
                    transaction.CardLast4       = json.Get("card")?.GetValue <string>("masked_number_last4");
                    transaction.CardExpMonth    = json.Get("card")?.GetValue <int>("expiry_month");
                    transaction.CardExpYear     = json.Get("card")?.GetValue <int>("expiry_year");
                    return(transaction);

                default:
                    break;
                }

                transaction.TransactionId       = json.GetValue <string>("id");
                transaction.BalanceAmount       = json.GetValue <string>("amount").ToAmount();
                transaction.Timestamp           = json.GetValue <string>("time_created");
                transaction.ResponseMessage     = json.GetValue <string>("status");
                transaction.ReferenceNumber     = json.GetValue <string>("reference");
                transaction.ClientTransactionId = json.GetValue <string>("reference");
                transaction.BatchSummary        = new BatchSummary {
                    BatchReference = json.GetValue <string>("batch_id")
                };
                transaction.Token              = json.Get("payment_method")?.GetValue <string>("id");
                transaction.AuthorizationCode  = json.Get("payment_method")?.GetValue <string>("result");
                transaction.CardType           = json.Get("payment_method")?.Get("card")?.GetValue <string>("brand");
                transaction.CardLast4          = json.Get("payment_method")?.Get("card")?.GetValue <string>("masked_number_last4");
                transaction.CvnResponseMessage = json.Get("payment_method")?.Get("card")?.GetValue <string>("cvv_result");
            }

            return(transaction);
        }
Example #19
0
        private Schedule HydrateSchedule(JsonDoc response)
        {
            var schedule = new Schedule();

            schedule.Key         = response.GetValue <string>("scheduleKey");
            schedule.Id          = response.GetValue <string>("scheduleIdentifier");
            schedule.CustomerKey = response.GetValue <string>("customerKey");
            schedule.Name        = response.GetValue <string>("scheduleName");
            schedule.Status      = response.GetValue <string>("scheduleStatus");
            schedule.PaymentKey  = response.GetValue <string>("paymentMethodKey");
            if (response.Has("subtotalAmount"))
            {
                var subtotal = response.Get("subtotalAmount");
                schedule.Amount   = subtotal.GetValue("value", AmountConverter);
                schedule.Currency = subtotal.GetValue <string>("currency");
            }
            if (response.Has("taxAmount"))
            {
                var taxAmount = response.Get("taxAmount");
                schedule.TaxAmount = taxAmount.GetValue("value", AmountConverter);
            }
            schedule.DeviceId        = response.GetValue <int>("DeviceId");
            schedule.StartDate       = response.GetValue("startDate", DateConverter);
            schedule.PaymentSchedule = response.GetValue("processingDateInfo", (value) => {
                if (value == null)
                {
                    return(PaymentSchedule.Dynamic);
                }
                var str = value.ToString();
                if (str == "Last")
                {
                    return(PaymentSchedule.LastDayOfTheMonth);
                }
                else if (str == "First")
                {
                    return(PaymentSchedule.FirstDayOfTheMonth);
                }
                return(PaymentSchedule.Dynamic);
            });
            schedule.Frequency         = response.GetValue <string>("frequency");
            schedule.EndDate           = response.GetValue("endDate", DateConverter);
            schedule.ReprocessingCount = response.GetValue <int>("reprocessingCount");
            schedule.EmailReceipt      = response.GetValue("emailReceipt", EnumConverter <EmailReceipt>);
            schedule.EmailNotification = response.GetValue("emailAdvanceNotice", (value) => {
                if (value == null)
                {
                    return(false);
                }
                return(value.ToString() == "No" ? false : true);
            });
            // dept repay indicator
            schedule.InvoiceNumber = response.GetValue <string>("invoiceNbr");
            schedule.PoNumber      = response.GetValue <string>("poNumber");
            schedule.Description   = response.GetValue <string>("Description");
            // statusSetDate
            schedule.NextProcessingDate = response.GetValue <DateTime?>("nextProcessingDate", DateConverter);
            // previousProcessingDate
            // approvedTransactionCount
            // failureCount
            // totalApprovedAmountToDate
            // numberOfPaymentsRemaining
            schedule.CancellationDate = response.GetValue("cancellationDate", DateConverter);
            // creationDate
            // lastChangeDate
            schedule.HasStarted = response.GetValue <bool>("scheduleStarted");
            return(schedule);
        }
Example #20
0
        public static TransactionSummary MapTransactionSummary(JsonDoc doc)
        {
            var summary = new TransactionSummary {
                TransactionId         = doc.GetValue <string>("id"),
                TransactionDate       = doc.GetValue <DateTime?>("time_created", DateConverter),
                TransactionStatus     = doc.GetValue <string>("status"),
                TransactionType       = doc.GetValue <string>("type"),
                Channel               = doc.GetValue <string>("channel"),
                Amount                = doc.GetValue <string>("amount").ToAmount(),
                Currency              = doc.GetValue <string>("currency"),
                ReferenceNumber       = doc.GetValue <string>("reference"),
                ClientTransactionId   = doc.GetValue <string>("reference"),
                TransactionLocalDate  = doc.GetValue <DateTime?>("time_created_reference", DateConverter),
                BatchSequenceNumber   = doc.GetValue <string>("batch_id"),
                Country               = doc.GetValue <string>("country"),
                OriginalTransactionId = doc.GetValue <string>("parent_resource_id"),
                DepositReference      = doc.GetValue <string>("deposit_id"),
                BatchCloseDate        = doc.GetValue <DateTime?>("batch_time_created", DateConverter),
                DepositDate           = doc.GetValue <DateTime?>("deposit_time_created", DateConverter),

                MerchantId        = doc.Get("system")?.GetValue <string>("mid"),
                MerchantHierarchy = doc.Get("system")?.GetValue <string>("hierarchy"),
                MerchantName      = doc.Get("system")?.GetValue <string>("name"),
                MerchantDbaName   = doc.Get("system")?.GetValue <string>("dba"),
            };

            if (doc.Has("payment_method"))
            {
                JsonDoc paymentMethod = doc.Get("payment_method");
                summary.GatewayResponseMessage = paymentMethod?.GetValue <string>("message");
                summary.EntryMode      = paymentMethod?.GetValue <string>("entry_mode");
                summary.CardHolderName = paymentMethod?.GetValue <string>("name");

                if (paymentMethod.Has("card"))
                {
                    JsonDoc card = paymentMethod?.Get("card");
                    summary.CardType               = card?.GetValue <string>("brand");
                    summary.AuthCode               = card?.GetValue <string>("authcode");
                    summary.BrandReference         = card?.GetValue <string>("brand_reference");
                    summary.AquirerReferenceNumber = card?.GetValue <string>("arn");
                    summary.MaskedCardNumber       = card?.GetValue <string>("masked_number_first6last4");
                    summary.PaymentType            = EnumConverter.GetMapping(Target.GP_API, PaymentMethodName.Card);
                }
                else if (paymentMethod.Has("digital_wallet"))
                {
                    JsonDoc digitalWallet = paymentMethod?.Get("digital_wallet");
                    summary.MaskedCardNumber = digitalWallet?.GetValue <string>("masked_token_first6last4");
                    summary.PaymentType      = EnumConverter.GetMapping(Target.GP_API, PaymentMethodName.DigitalWallet);
                }
                else if (paymentMethod.Has("bank_transfer"))
                {
                    JsonDoc bankTransfer = paymentMethod?.Get("bank_transfer");
                    summary.AccountNumberLast4 = bankTransfer?.GetValue <string>("masked_account_number_last4");
                    summary.AccountType        = bankTransfer?.GetValue <string>("account_type");
                    summary.PaymentType        = EnumConverter.GetMapping(Target.GP_API, PaymentMethodName.BankTransfer);
                }
                else if (paymentMethod.Has("apm"))
                {
                    JsonDoc apm = paymentMethod?.Get("apm");
                    var     alternativePaymentResponse = new AlternativePaymentResponse();
                    alternativePaymentResponse.RedirectUrl       = apm?.GetValue <string>("redirect_url");
                    alternativePaymentResponse.ProviderName      = apm?.GetValue <string>("provider");
                    alternativePaymentResponse.ProviderReference = apm?.GetValue <string>("provider_reference");
                    summary.AlternativePaymentResponse           = alternativePaymentResponse;
                    summary.PaymentType = EnumConverter.GetMapping(Target.GP_API, PaymentMethodName.APM);
                }
            }
            return(summary);
        }
Example #21
0
        public void MapSettlementDisputeSummaryTest_NullDate()
        {
            string rawJson = "{\"id\":\"DIS_812\",\"status\":\"FUNDED\",\"stage\":\"CHARGEBACK\",\"stage_time_created\":\"\",\"amount\":\"200\",\"currency\":\"GBP\",\"reason_code\":\"PM\",\"reason_description\":\"Paid by Other Means\",\"time_to_respond_by\":\"\",\"result\":\"LOST\",\"funding_type\":\"DEBIT\",\"deposit_time_created\":\"\",\"deposit_id\":\"DEP_2342423443\",\"last_adjustment_amount\":\"\",\"last_adjustment_currency\":\"\",\"last_adjustment_funding\":\"\",\"last_adjustment_time_created\":\"\",\"system\":{\"mid\":\"11112334\",\"tid\":\"22229876\",\"hierarchy\":\"000-00-000-000-000\",\"name\":\"MERCHANT ABC INC.\",\"dba\":\"MERCHANT XYZ INC.\"},\"transaction\":{\"time_created\":\"\",\"merchant_time_created\":\"\",\"type\":\"SALE\",\"amount\":\"200\",\"currency\":\"GBP\",\"reference\":\"28012076eb6M\",\"payment_method\":{\"card\":{\"masked_number_first6last4\":\"379132XXXXX1007\",\"arn\":\"71400011203688701393903\",\"brand\":\"AMEX\",\"authcode\":\"129623\",\"brand_reference\":\"MWE1P0JG80110\"}}}}";

            JsonDoc doc = JsonDoc.Parse(rawJson);

            // Act
            DisputeSummary dispute = GpApiMapping.MapSettlementDisputeSummary(doc);

            // Assert
            Assert.AreEqual(doc.GetValue <string>("id"), dispute.CaseId);
            Assert.IsNull(dispute.CaseIdTime);
            Assert.AreEqual(doc.GetValue <string>("status"), dispute.CaseStatus);
            Assert.AreEqual(doc.GetValue <string>("stage"), dispute.CaseStage);
            Assert.AreEqual(doc.GetValue <string>("amount").ToAmount(), dispute.CaseAmount);
            Assert.AreEqual(doc.GetValue <string>("currency"), dispute.CaseCurrency);
            Assert.AreEqual(doc.GetValue <string>("last_adjustment_amount").ToAmount(), dispute.LastAdjustmentAmount);
            Assert.AreEqual(doc.GetValue <string>("last_adjustment_currency"), dispute.LastAdjustmentCurrency);
            Assert.AreEqual(doc.GetValue <string>("last_adjustment_funding"), dispute.LastAdjustmentFunding);
            Assert.AreEqual(doc.Get("system")?.GetValue <string>("mid"), dispute.CaseMerchantId);
            Assert.AreEqual(doc.Get("system")?.GetValue <string>("tid"), dispute.CaseTerminalId);
            Assert.AreEqual(doc.Get("system")?.GetValue <string>("hierarchy"), dispute.MerchantHierarchy);
            Assert.AreEqual(doc.Get("system")?.GetValue <string>("name"), dispute.MerchantName);
            Assert.AreEqual(doc.Get("system")?.GetValue <string>("dba"), dispute.MerchantDbaName);
            Assert.AreEqual(doc.GetValue <string>("reason_code"), dispute.ReasonCode);
            Assert.AreEqual(doc.GetValue <string>("reason_description"), dispute.Reason);
            Assert.AreEqual(doc.GetValue <string>("result"), dispute.Result);
            Assert.IsNull(dispute.TransactionTime);
            Assert.AreEqual(doc.Get("transaction")?.GetValue <string>("type"), dispute.TransactionType);
            Assert.AreEqual(doc.Get("transaction")?.GetValue <string>("amount").ToAmount(), dispute.TransactionAmount);
            Assert.AreEqual(doc.Get("transaction")?.GetValue <string>("currency"), dispute.TransactionCurrency);
            Assert.AreEqual(doc.Get("transaction")?.GetValue <string>("reference"), dispute.TransactionReferenceNumber);
            Assert.AreEqual(doc.Get("transaction")?.Get("payment_method")?.Get("card")?.GetValue <string>("masked_number_first6last4"), dispute.TransactionMaskedCardNumber);
            Assert.AreEqual(doc.Get("transaction")?.Get("payment_method")?.Get("card")?.GetValue <string>("arn"), dispute.TransactionARN);
            Assert.AreEqual(doc.Get("transaction")?.Get("payment_method")?.Get("card")?.GetValue <string>("brand"), dispute.TransactionCardType);
            Assert.AreEqual(doc.Get("transaction")?.Get("payment_method")?.Get("card")?.GetValue <string>("authcode"), dispute.TransactionAuthCode);
            Assert.IsNull(dispute.RespondByDate);
            Assert.IsNull(dispute.DepositDate);
            Assert.AreEqual(doc.GetValue <String>("deposit_id"), dispute.DepositReference);
        }
Example #22
0
        public static Transaction Map3DSecureData(string rawResponse)
        {
            if (!string.IsNullOrEmpty(rawResponse))
            {
                JsonDoc json = JsonDoc.Parse(rawResponse);

                var transaction = new Transaction
                {
                    ThreeDSecure = new ThreeDSecure
                    {
                        ServerTransactionId = !string.IsNullOrEmpty(json.GetValue <string>("id")) ?
                                              json.GetValue <string>("id") :
                                              json.Get("three_ds")?.GetValue <string>("server_trans_ref"),
                        MessageVersion = json.Get("three_ds")?.GetValue <string>("message_version"),
                        Version        = Parse3DSVersion(json.Get("three_ds")?.GetValue <string>("message_version")),
                        Status         = json.GetValue <string>("status"),
                        DirectoryServerStartVersion = json.Get("three_ds")?.GetValue <string>("ds_protocol_version_start"),
                        DirectoryServerEndVersion   = json.Get("three_ds")?.GetValue <string>("ds_protocol_version_end"),
                        AcsStartVersion             = json.Get("three_ds")?.GetValue <string>("acs_protocol_version_start"),
                        AcsEndVersion              = json.Get("three_ds")?.GetValue <string>("acs_protocol_version_end"),
                        Enrolled                   = json.Get("three_ds")?.GetValue <string>("enrolled_status"),
                        Eci                        = !string.IsNullOrEmpty(json.Get("three_ds")?.GetValue <string>("eci")) ? json.Get("three_ds")?.GetValue <string>("eci") : null,
                        AcsInfoIndicator           = json.Get("three_ds")?.GetArray <string>("acs_info_indicator"),
                        ChallengeMandated          = json.Get("three_ds")?.GetValue <string>("challenge_status") == "MANDATED",
                        PayerAuthenticationRequest = (!string.IsNullOrEmpty(json.Get("three_ds").GetValue <string>("acs_challenge_request_url")) && json.GetValue <string>("status") == "CHALLENGE_REQUIRED") ?
                                                     json.Get("three_ds")?.GetValue <string>("challenge_value") :
                                                     json.Get("three_ds")?.Get("method_data")?.GetValue <string>("encoded_method_data"),
                        IssuerAcsUrl = (!string.IsNullOrEmpty(json.Get("three_ds").GetValue <string>("acs_challenge_request_url")) && json.GetValue <string>("status") == "CHALLENGE_REQUIRED") ?
                                       json.Get("three_ds")?.GetValue <string>("acs_challenge_request_url") :
                                       json.Get("three_ds")?.GetValue <string>("method_url"),
                        Currency                     = json.GetValue <string>("currency"),
                        Amount                       = json.GetValue <string>("amount").ToAmount(),
                        AuthenticationValue          = json.Get("three_ds")?.GetValue <string>("authentication_value"),
                        DirectoryServerTransactionId = json.Get("three_ds")?.GetValue <string>("ds_trans_ref"),
                        AcsTransactionId             = json.Get("three_ds")?.GetValue <string>("acs_trans_ref"),
                        StatusReason                 = json.Get("three_ds")?.GetValue <string>("status_reason"),
                        MessageCategory              = json.Get("three_ds")?.GetValue <string>("message_category"),
                        MessageType                  = json.Get("three_ds")?.GetValue <string>("message_type"),
                        SessionDataFieldName         = json.Get("three_ds")?.GetValue <string>("session_data_field_name"),
                        ChallengeReturnUrl           = json.Get("notifications")?.GetValue <string>("challenge_return_url"),
                        LiabilityShift               = json.Get("three_ds")?.GetValue <string>("liability_shift"),
                        AuthenticationSource         = json.Get("three_ds")?.GetValue <string>("authentication_source"),
                        AuthenticationType           = json.Get("three_ds")?.GetValue <string>("authentication_request_type"),
                        //AcsInfoIndicator = json.Get("three_ds")?.GetArray<string>("acs_decoupled_response_indicator"),
                        WhitelistStatus   = json.Get("three_ds")?.GetValue <string>("whitelist_status"),
                        MessageExtensions = new List <MessageExtension>()
                    }
                };

                // Mobile data
                if (!string.IsNullOrEmpty(json.GetValue <string>("source")) && json.GetValue <string>("source").Equals("MOBILE_SDK"))
                {
                    if (json.Get("three_ds")?.Get("mobile_data") != null)
                    {
                        JsonDoc mobile_data = json.Get("three_ds").Get("mobile_data");

                        transaction.ThreeDSecure.PayerAuthenticationRequest = mobile_data.GetValue <string>("acs_signed_content");

                        if (mobile_data.Get("acs_rendering_type").HasKeys())
                        {
                            JsonDoc acs_rendering_type = mobile_data.Get("acs_rendering_type");
                            transaction.ThreeDSecure.AcsInterface  = acs_rendering_type.GetValue <string>("acs_interface");
                            transaction.ThreeDSecure.AcsUiTemplate = acs_rendering_type.GetValue <string>("acs_ui_template");
                        }
                    }
                }

                var messageExtensions = json.Get("three_ds")?.GetEnumerator("message_extension");

                if (messageExtensions != null)
                {
                    foreach (JsonDoc messageExtension in messageExtensions)
                    {
                        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")
                        };
                        transaction.ThreeDSecure.MessageExtensions.Add(msgExtension);
                    }
                }

                return(transaction);
            }
            return(new Transaction());
        }
Example #23
0
        public Transaction ProcessAuthorization(AuthorizationBuilder builder)
        {
            if (string.IsNullOrEmpty(SessionToken))
            {
                SignIn();
            }

            var paymentMethod = new JsonDoc()
                                .Set("entry_mode", GetEntryMode(builder)); // [MOTO, ECOM, IN_APP, CHIP, SWIPE, MANUAL, CONTACTLESS_CHIP, CONTACTLESS_SWIPE]

            if (builder.PaymentMethod is ICardData)
            {
                var cardData = builder.PaymentMethod as ICardData;

                var card = new JsonDoc()
                           .Set("number", cardData.Number)
                           .Set("expiry_month", cardData.ExpMonth.HasValue ? cardData.ExpMonth.ToString().PadLeft(2, '0') : string.Empty)
                           .Set("expiry_year", cardData.ExpYear.HasValue ? cardData.ExpYear.ToString().PadLeft(4, '0').Substring(2, 2) : string.Empty)
                           //.Set("track", "")
                           .Set("tag", builder.TagData)
                           .Set("cvv", cardData.Cvn)
                           .Set("avs_address", builder.BillingAddress?.StreetAddress1)
                           .Set("avs_postal_code", builder.BillingAddress?.PostalCode)
                           .Set("funding", builder.PaymentMethod?.PaymentMethodType == PaymentMethodType.Debit ? "DEBIT" : "CREDIT") // [DEBIT, CREDIT]
                           .Set("authcode", builder.OfflineAuthCode);
                //.Set("brand_reference", "")

                if (builder.TransactionType == TransactionType.Verify)
                {
                    if (builder.RequestMultiUseToken)
                    {
                        var tokenizationData = new JsonDoc()
                                               .Set("account_name", TokenizationAccountName)
                                               .Set("reference", builder.ClientTransactionId ?? Guid.NewGuid().ToString())
                                               .Set("name", "")
                                               .Set("card", card);

                        var tokenizationResponse = DoTransaction(HttpMethod.Post, "/ucp/payment-methods", tokenizationData.ToString());

                        return(MapResponse(tokenizationResponse));
                    }
                    else
                    {
                        var tokenizationResponse = DoTransaction(HttpMethod.Get, $"/ucp/payment-methods/{(builder.PaymentMethod as ITokenizable).Token}");

                        return(MapResponse(tokenizationResponse));
                    }
                }

                if (builder.EmvLastChipRead != null)
                {
                    card.Set("chip_condition", EnumConverter.GetMapping(Target.GP_API, builder.EmvLastChipRead)); // [PREV_SUCCESS, PREV_FAILED]
                }
                if (cardData.CvnPresenceIndicator == CvnPresenceIndicator.Present || cardData.CvnPresenceIndicator == CvnPresenceIndicator.Illegible || cardData.CvnPresenceIndicator == CvnPresenceIndicator.NotOnCard)
                {
                    card.Set("cvv_indicator", EnumConverter.GetMapping(Target.GP_API, cardData.CvnPresenceIndicator)); // [ILLEGIBLE, NOT_PRESENT, PRESENT]
                }

                paymentMethod.Set("card", card);
            }
            else if (builder.PaymentMethod is ITrackData)
            {
                var track = builder.PaymentMethod as ITrackData;

                var card = new JsonDoc()
                           .Set("track", track.Value)
                           .Set("tag", builder.TagData)
                           //.Set("cvv", cardData.Cvn)
                           //.Set("cvv_indicator", "") // [ILLEGIBLE, NOT_PRESENT, PRESENT]
                           .Set("avs_address", builder.BillingAddress?.StreetAddress1)
                           .Set("avs_postal_code", builder.BillingAddress?.PostalCode)
                           .Set("authcode", builder.OfflineAuthCode);
                //.Set("brand_reference", "")

                if (builder.TransactionType == TransactionType.Sale)
                {
                    card.Set("number", track.Pan);
                    card.Set("expiry_month", track.Expiry?.Substring(2, 2));
                    card.Set("expiry_year", track.Expiry?.Substring(0, 2));
                    card.Set("chip_condition", EnumConverter.GetMapping(Target.GP_API, builder.EmvLastChipRead));                  // [PREV_SUCCESS, PREV_FAILED]
                    card.Set("funding", builder.PaymentMethod?.PaymentMethodType == PaymentMethodType.Debit ? "DEBIT" : "CREDIT"); // [DEBIT, CREDIT]
                }

                paymentMethod.Set("card", card);
            }

            // pin block
            if (builder.PaymentMethod is IPinProtected)
            {
                paymentMethod.Get("card")?.Set("pin_block", ((IPinProtected)builder.PaymentMethod).PinBlock);
            }

            // authentication
            if (builder.PaymentMethod is CreditCardData)
            {
                paymentMethod.Set("name", (builder.PaymentMethod as CreditCardData).CardHolderName);

                var secureEcom = (builder.PaymentMethod as CreditCardData).ThreeDSecure;
                if (secureEcom != null)
                {
                    var authentication = new JsonDoc()
                                         .Set("xid", secureEcom.Xid)
                                         .Set("cavv", secureEcom.Cavv)
                                         .Set("eci", secureEcom.Eci);
                    //.Set("mac", ""); //A message authentication code submitted to confirm integrity of the request.

                    paymentMethod.Set("authentication", authentication);
                }
            }

            // encryption
            if (builder.PaymentMethod is IEncryptable)
            {
                var encryptionData = ((IEncryptable)builder.PaymentMethod).EncryptionData;

                if (encryptionData != null)
                {
                    var encryption = new JsonDoc()
                                     .Set("version", encryptionData.Version);

                    if (!string.IsNullOrEmpty(encryptionData.KTB))
                    {
                        encryption.Set("method", "KTB");
                        encryption.Set("info", encryptionData.KTB);
                    }
                    else if (!string.IsNullOrEmpty(encryptionData.KSN))
                    {
                        encryption.Set("method", "KSN");
                        encryption.Set("info", encryptionData.KSN);
                    }

                    if (encryption.Has("info"))
                    {
                        paymentMethod.Set("encryption", encryption);
                    }
                }
            }

            var data = new JsonDoc()
                       .Set("account_name", TransactionProcessingAccountName)
                       .Set("type", builder.TransactionType == TransactionType.Refund ? "REFUND" : "SALE") // [SALE, REFUND]
                       .Set("channel", EnumConverter.GetMapping(Target.GP_API, Channel))                   // [CP, CNP]
                       .Set("capture_mode", GetCaptureMode(builder))                                       // [AUTO, LATER, MULTIPLE]
                                                                                                           //.Set("remaining_capture_count", "") //Pending Russell
                       .Set("authorization_mode", builder.AllowPartialAuth ? "PARTIAL" : "WHOLE")          // [PARTIAL, WHOLE]
                       .Set("amount", builder.Amount.ToNumericCurrencyString())
                       .Set("currency", builder.Currency)
                       .Set("reference", builder.ClientTransactionId ?? Guid.NewGuid().ToString())
                       .Set("description", builder.Description)
                       .Set("order_reference", builder.OrderId)
                       //.Set("initiator", "") // [PAYER, MERCHANT] //default to PAYER
                       .Set("gratuity_amount", builder.Gratuity.ToNumericCurrencyString())
                       .Set("cashback_amount", builder.CashBackAmount.ToNumericCurrencyString())
                       .Set("surcharge_amount", builder.SurchargeAmount.ToNumericCurrencyString())
                       .Set("convenience_amount", builder.ConvenienceAmount.ToNumericCurrencyString())
                       .Set("country", builder.BillingAddress?.Country ?? "US")
                       //.Set("language", EnumConverter.GetMapping(Target.GP_API, Language))
                       .Set("ip_address", builder.CustomerIpAddress)
                       //.Set("site_reference", "") //
                       .Set("payment_method", paymentMethod);

            var response = DoTransaction(HttpMethod.Post, "/ucp/transactions", data.ToString());

            return(MapResponse(response));
        }
        internal static GpApiRequest BuildRequest(AuthorizationBuilder builder, GpApiConnector gateway)
        {
            var merchantUrl   = !string.IsNullOrEmpty(gateway.GpApiConfig.MerchantId) ? $"/merchants/{gateway.GpApiConfig.MerchantId}" : string.Empty;
            var paymentMethod = new JsonDoc()
                                .Set("entry_mode", GetEntryMode(builder, gateway.GpApiConfig.Channel)); // [MOTO, ECOM, IN_APP, CHIP, SWIPE, MANUAL, CONTACTLESS_CHIP, CONTACTLESS_SWIPE]

            paymentMethod.Set("narrative", !string.IsNullOrEmpty(builder.DynamicDescriptor) ? builder.DynamicDescriptor : null);
            if (builder.PaymentMethod is CreditCardData && (builder.TransactionModifier == TransactionModifier.EncryptedMobile || builder.TransactionModifier == TransactionModifier.DecryptedMobile))
            {
                var digitalWallet  = new JsonDoc();
                var creditCardData = (builder.PaymentMethod as CreditCardData);
                //Digital Wallet
                if (builder.TransactionModifier == TransactionModifier.EncryptedMobile)
                {
                    digitalWallet
                    .Set("payment_token", JsonDoc.Parse(creditCardData.Token));
                }
                else if (builder.TransactionModifier == TransactionModifier.DecryptedMobile)
                {
                    var tokenFormat = DigitalWalletTokenFormat.CARD_NUMBER;
                    digitalWallet
                    .Set("token", creditCardData.Token)
                    .Set("token_format", DigitalWalletTokenFormat.CARD_NUMBER)
                    .Set("expiry_month", creditCardData.ExpMonth.HasValue ? creditCardData.ExpMonth.ToString().PadLeft(2, '0') : null)
                    .Set("expiry_year", creditCardData.ExpYear.HasValue ? creditCardData.ExpYear.ToString().PadLeft(4, '0').Substring(2, 2) : null)
                    .Set("cryptogram", creditCardData.Cryptogram)
                    .Set("eci", creditCardData.Eci);
                }
                digitalWallet.Set("provider", (builder.PaymentMethod as CreditCardData).MobileType);
                paymentMethod.Set("digital_wallet", digitalWallet);
            }
            else
            {
                if (builder.PaymentMethod is ICardData)
                {
                    var cardData = builder.PaymentMethod as ICardData;

                    var card = new JsonDoc()
                               .Set("number", cardData.Number)
                               .Set("expiry_month", cardData.ExpMonth.HasValue ? cardData.ExpMonth.ToString().PadLeft(2, '0') : null)
                               .Set("expiry_year", cardData.ExpYear.HasValue ? cardData.ExpYear.ToString().PadLeft(4, '0').Substring(2, 2) : null)
                               //.Set("track", "")
                               .Set("tag", builder.TagData)
                               .Set("cvv", cardData.Cvn)
                               .Set("avs_address", builder.BillingAddress?.StreetAddress1)
                               .Set("avs_postal_code", builder.BillingAddress?.PostalCode)
                               .Set("authcode", builder.OfflineAuthCode)
                               .Set("brand_reference", builder.CardBrandTransactionId);

                    card.Set("chip_condition", EnumConverter.GetMapping(Target.GP_API, builder.EmvChipCondition)); // [PREV_SUCCESS, PREV_FAILED]

                    if (!(builder.TransactionType == TransactionType.Tokenize || builder.TransactionType == TransactionType.Verify))
                    {
                        card.Set("cvv_indicator", cardData.CvnPresenceIndicator != 0 ? EnumConverter.GetMapping(Target.GP_API, cardData.CvnPresenceIndicator) : null); // [ILLEGIBLE, NOT_PRESENT, PRESENT]
                        card.Set("funding", builder.PaymentMethod?.PaymentMethodType == PaymentMethodType.Debit ? "DEBIT" : "CREDIT");                                 // [DEBIT, CREDIT]
                    }

                    var hasToken = builder.PaymentMethod is ITokenizable tokenData && !string.IsNullOrEmpty(tokenData.Token);

                    if (!hasToken)
                    {
                        paymentMethod.Set("card", card);
                    }


                    if (builder.TransactionType == TransactionType.Tokenize)
                    {
                        var tokenizationData = new JsonDoc()
                                               .Set("account_name", gateway.GpApiConfig.AccessTokenInfo.TokenizationAccountName)
                                               .Set("reference", builder.ClientTransactionId ?? Guid.NewGuid().ToString())
                                               .Set("usage_mode", EnumConverter.GetMapping(Target.GP_API, builder.PaymentMethodUsageMode))
                                               .Set("card", card);

                        return(new GpApiRequest {
                            Verb = HttpMethod.Post,
                            Endpoint = $"{merchantUrl}/payment-methods",
                            RequestBody = tokenizationData.ToString(),
                        });
                    }
                    else if (builder.TransactionType == TransactionType.DccRateLookup)
                    {
                        // tokenized payment method
                        if (builder.PaymentMethod is ITokenizable)
                        {
                            string token = ((ITokenizable)builder.PaymentMethod).Token;
                            if (!string.IsNullOrEmpty(token))
                            {
                                paymentMethod.Set("id", token);
                            }
                        }

                        var RequestData = new JsonDoc()
                                          .Set("account_name", gateway.GpApiConfig.AccessTokenInfo.TransactionProcessingAccountName)
                                          .Set("channel", EnumConverter.GetMapping(Target.GP_API, gateway.GpApiConfig.Channel))
                                          .Set("reference", builder.ClientTransactionId ?? Guid.NewGuid().ToString())
                                          .Set("amount", builder.Amount.ToNumericCurrencyString())
                                          .Set("currency", builder.Currency)
                                          .Set("country", gateway.GpApiConfig.Country)
                                          .Set("payment_method", paymentMethod);

                        return(new GpApiRequest
                        {
                            Verb = HttpMethod.Post,
                            Endpoint = $"{merchantUrl}/currency-conversions",
                            RequestBody = RequestData.ToString(),
                        });
                    }
                    else if (builder.TransactionType == TransactionType.Verify)
                    {
                        if (builder.RequestMultiUseToken && string.IsNullOrEmpty((builder.PaymentMethod as ITokenizable).Token))
                        {
                            var tokenizationData = new JsonDoc()
                                                   .Set("account_name", gateway.GpApiConfig.AccessTokenInfo.TokenizationAccountName)
                                                   .Set("reference", builder.ClientTransactionId ?? Guid.NewGuid().ToString())
                                                   .Set("usage_mode", EnumConverter.GetMapping(Target.GP_API, builder.PaymentMethodUsageMode))
                                                   .Set("fingerprint_mode", builder.CustomerData?.DeviceFingerPrint ?? null)
                                                   .Set("card", card);

                            return(new GpApiRequest {
                                Verb = HttpMethod.Post,
                                Endpoint = $"{merchantUrl}/payment-methods",
                                RequestBody = tokenizationData.ToString(),
                            });
                        }
                        else
                        {
                            var verificationData = new JsonDoc()
                                                   .Set("account_name", gateway.GpApiConfig.AccessTokenInfo.TransactionProcessingAccountName)
                                                   .Set("channel", EnumConverter.GetMapping(Target.GP_API, gateway.GpApiConfig.Channel))
                                                   .Set("reference", builder.ClientTransactionId ?? Guid.NewGuid().ToString())
                                                   .Set("currency", builder.Currency)
                                                   .Set("country", gateway.GpApiConfig.Country)
                                                   .Set("payment_method", paymentMethod);

                            if (builder.PaymentMethod is ITokenizable && !string.IsNullOrEmpty((builder.PaymentMethod as ITokenizable).Token))
                            {
                                verificationData.Remove("payment_method");
                                verificationData.Set("payment_method", new JsonDoc()
                                                     .Set("entry_mode", GetEntryMode(builder, gateway.GpApiConfig.Channel))
                                                     .Set("id", (builder.PaymentMethod as ITokenizable).Token)
                                                     .Set("fingerprint_mode", builder.CustomerData?.DeviceFingerPrint ?? null)
                                                     );
                            }

                            return(new GpApiRequest {
                                Verb = HttpMethod.Post,
                                Endpoint = $"{merchantUrl}/verifications",
                                RequestBody = verificationData.ToString(),
                            });
                        }
                    }
                }
                else if (builder.PaymentMethod is ITrackData)
                {
                    var track = builder.PaymentMethod as ITrackData;

                    var card = new JsonDoc()
                               .Set("track", track.Value)
                               .Set("tag", builder.TagData)
                               .Set("avs_address", builder.BillingAddress?.StreetAddress1)
                               .Set("avs_postal_code", builder.BillingAddress?.PostalCode)
                               .Set("authcode", builder.OfflineAuthCode);

                    if (builder.TransactionType == TransactionType.Verify)
                    {
                        paymentMethod.Set("card", card);

                        var verificationData = new JsonDoc()
                                               .Set("account_name", gateway.GpApiConfig.AccessTokenInfo.TransactionProcessingAccountName)
                                               .Set("channel", EnumConverter.GetMapping(Target.GP_API, gateway.GpApiConfig.Channel))
                                               .Set("reference", builder.ClientTransactionId ?? Guid.NewGuid().ToString())
                                               .Set("currency", builder.Currency)
                                               .Set("country", gateway.GpApiConfig.Country)
                                               .Set("payment_method", paymentMethod)
                                               .Set("fingerprint_mode", builder.CustomerData?.DeviceFingerPrint ?? null);

                        return(new GpApiRequest {
                            Verb = HttpMethod.Post,
                            Endpoint = $"{merchantUrl}/verifications",
                            RequestBody = verificationData.ToString(),
                        });
                    }

                    if (builder.TransactionType == TransactionType.Sale || builder.TransactionType == TransactionType.Refund)
                    {
                        if (string.IsNullOrEmpty(track.Value))
                        {
                            card.Set("number", track.Pan);
                            card.Set("expiry_month", track.Expiry?.Substring(2, 2));
                            card.Set("expiry_year", track.Expiry?.Substring(0, 2));
                        }
                        if (string.IsNullOrEmpty(builder.TagData))
                        {
                            card.Set("chip_condition", EnumConverter.GetMapping(Target.GP_API, builder.EmvChipCondition)); // [PREV_SUCCESS, PREV_FAILED]
                        }
                    }

                    if (builder.TransactionType == TransactionType.Sale)
                    {
                        card.Set("funding", builder.PaymentMethod?.PaymentMethodType == PaymentMethodType.Debit ? "DEBIT" : "CREDIT"); // [DEBIT, CREDIT]
                    }

                    paymentMethod.Set("card", card);
                }

                // tokenized payment method
                if (builder.PaymentMethod is ITokenizable)
                {
                    string token = ((ITokenizable)builder.PaymentMethod).Token;
                    if (!string.IsNullOrEmpty(token))
                    {
                        paymentMethod.Set("id", token);
                    }
                }
            }
            // payment method storage mode
            if (builder.RequestMultiUseToken)
            {
                //ToDo: there might be a typo: should be storage_mode
                paymentMethod.Set("storage_mode", "ON_SUCCESS");
            }

            // pin block
            if (builder.PaymentMethod is IPinProtected)
            {
                paymentMethod.Get("card")?.Set("pin_block", ((IPinProtected)builder.PaymentMethod).PinBlock);
            }

            // authentication
            if (builder.PaymentMethod is CreditCardData)
            {
                paymentMethod.Set("name", (builder.PaymentMethod as CreditCardData).CardHolderName);

                var secureEcom = (builder.PaymentMethod as CreditCardData).ThreeDSecure;
                if (secureEcom != null)
                {
                    var authentication = new JsonDoc().Set("id", secureEcom.ServerTransactionId);

                    paymentMethod.Set("authentication", authentication);
                }

                paymentMethod.Set("fingerprint_mode", builder.CustomerData?.DeviceFingerPrint ?? null);
            }

            if (builder.PaymentMethod is EBT)
            {
                paymentMethod.Set("name", (builder.PaymentMethod as EBT).CardHolderName);
            }

            if (builder.PaymentMethod is eCheck)
            {
                eCheck check = (builder.PaymentMethod as eCheck);
                paymentMethod.Set("name", check.CheckHolderName);

                var bankTransfer = new JsonDoc()
                                   .Set("account_number", check.AccountNumber)
                                   .Set("account_type", (check.AccountType != null) ? EnumConverter.GetMapping(Target.GP_API, check.AccountType) : null)
                                   .Set("check_reference", check.CheckReference)
                                   .Set("sec_code", check.SecCode)
                                   .Set("narrative", check.MerchantNotes);

                var bank = new JsonDoc()
                           .Set("code", check.RoutingNumber)
                           .Set("name", check.BankName);

                var address = new JsonDoc()
                              .Set("line_1", check.BankAddress?.StreetAddress1)
                              .Set("line_2", check.BankAddress?.StreetAddress2)
                              .Set("line_3", check.BankAddress?.StreetAddress3)
                              .Set("city", check.BankAddress?.City)
                              .Set("postal_code", check.BankAddress?.PostalCode)
                              .Set("state", check.BankAddress?.State)
                              .Set("country", check.BankAddress?.CountryCode);

                bank.Set("address", address);

                bankTransfer.Set("bank", bank);

                paymentMethod.Set("bank_transfer", bankTransfer);
            }

            if (builder.PaymentMethod is AlternativePaymentMethod)
            {
                var alternatepaymentMethod = (AlternativePaymentMethod)builder.PaymentMethod;

                paymentMethod.Set("name", alternatepaymentMethod.AccountHolderName);

                var apm = new JsonDoc()
                          .Set("provider", alternatepaymentMethod.AlternativePaymentMethodType?.ToString()?.ToLower())
                          .Set("address_override_mode", alternatepaymentMethod.AddressOverrideMode);
                paymentMethod.Set("apm", apm);
            }

            // encryption
            if (builder.PaymentMethod is IEncryptable)
            {
                var encryptionData = ((IEncryptable)builder.PaymentMethod).EncryptionData;

                if (encryptionData != null)
                {
                    var encryption = new JsonDoc()
                                     .Set("version", encryptionData.Version);

                    if (!string.IsNullOrEmpty(encryptionData.KTB))
                    {
                        encryption.Set("method", "KTB");
                        encryption.Set("info", encryptionData.KTB);
                    }
                    else if (!string.IsNullOrEmpty(encryptionData.KSN))
                    {
                        encryption.Set("method", "KSN");
                        encryption.Set("info", encryptionData.KSN);
                    }

                    if (encryption.Has("info"))
                    {
                        paymentMethod.Set("encryption", encryption);
                    }
                }
            }

            if (builder.TransactionType == TransactionType.Create && builder.PayLinkData is PayLinkData)
            {
                var payLinkData = builder.PayLinkData;
                var requestData = new JsonDoc()
                                  .Set("usage_limit", payLinkData.UsageLimit.ToString())
                                  .Set("usage_mode", EnumConverter.GetMapping(Target.GP_API, payLinkData.UsageMode))
                                  .Set("images", payLinkData.Images)
                                  .Set("description", builder.Description ?? null)
                                  .Set("type", payLinkData.Type?.ToString())
                                  .Set("expiration_date", payLinkData.ExpirationDate ?? null);

                var transaction = new JsonDoc()
                                  .Set("country", gateway.GpApiConfig.Country)
                                  .Set("amount", builder.Amount.ToNumericCurrencyString())
                                  .Set("channel", EnumConverter.GetMapping(Target.GP_API, gateway.GpApiConfig.Channel))
                                  .Set("currency", builder.Currency)
                                  .Set("allowed_payment_methods", GetAllowedPaymentMethod(payLinkData.AllowedPaymentMethods));

                requestData.Set("transactions", transaction)
                .Set("reference", builder.ClientTransactionId ?? Guid.NewGuid().ToString())
                .Set("shipping_amount", payLinkData.ShippingAmount.ToNumericCurrencyString())
                .Set("shippable", payLinkData.IsShippable?.ToString() ?? false.ToString())
                .Set("account_name", gateway.GpApiConfig.AccessTokenInfo.TransactionProcessingAccountName)
                .Set("name", payLinkData.Name ?? null);

                var notification = new JsonDoc()
                                   .Set("cancel_url", payLinkData.CancelUrl)
                                   .Set("return_url", payLinkData.ReturnUrl)
                                   .Set("status_url", payLinkData.StatusUpdateUrl);

                requestData.Set("notifications", notification)
                .Set("status", payLinkData.Status.ToString());

                return(new GpApiRequest
                {
                    Verb = HttpMethod.Post,
                    Endpoint = $"{merchantUrl}/links",
                    RequestBody = requestData.ToString(),
                });
            }

            var data = new JsonDoc()
                       .Set("account_name", gateway.GpApiConfig.AccessTokenInfo.TransactionProcessingAccountName)
                       .Set("type", builder.TransactionType == TransactionType.Refund ? "REFUND" : "SALE")   // [SALE, REFUND]
                       .Set("channel", EnumConverter.GetMapping(Target.GP_API, gateway.GpApiConfig.Channel)) // [CP, CNP]
                       .Set("capture_mode", GetCaptureMode(builder))                                         // [AUTO, LATER, MULTIPLE]
                                                                                                             //.Set("remaining_capture_count", "") //Pending Russell
                       .Set("authorization_mode", builder.AllowPartialAuth ? "PARTIAL" : null)
                       .Set("amount", builder.Amount.ToNumericCurrencyString())
                       .Set("currency", builder.Currency)
                       .Set("reference", builder.ClientTransactionId ?? Guid.NewGuid().ToString())
                       .Set("description", builder.Description)
                       //.Set("order_reference", builder.OrderId)
                       .Set("gratuity_amount", builder.Gratuity.ToNumericCurrencyString())
                       .Set("cashback_amount", builder.CashBackAmount.ToNumericCurrencyString())
                       .Set("surcharge_amount", builder.SurchargeAmount.ToNumericCurrencyString())
                       .Set("convenience_amount", builder.ConvenienceAmount.ToNumericCurrencyString())
                       .Set("country", gateway.GpApiConfig.Country)
                       //.Set("language", EnumConverter.GetMapping(Target.GP_API, Language))
                       .Set("ip_address", builder.CustomerIpAddress)
                       //.Set("site_reference", "") //
                       .Set("currency_conversion", !string.IsNullOrEmpty(builder.DccRateData?.DccId) ? new JsonDoc().Set("id", builder.DccRateData.DccId) : null)
                       .Set("payment_method", paymentMethod)
                       .Set("link", !string.IsNullOrEmpty(builder.PaymentLinkId) ? new JsonDoc()
                            .Set("id", builder.PaymentLinkId) : null);

            if (builder.PaymentMethod is eCheck || builder.PaymentMethod is AlternativePaymentMethod)
            {
                data.Set("payer", SetPayerInformation(builder));
            }

            // set order reference
            if (!string.IsNullOrEmpty(builder.OrderId))
            {
                var order = new JsonDoc()
                            .Set("reference", builder.OrderId);

                data.Set("order", order);
            }

            if (builder.PaymentMethod is AlternativePaymentMethod)
            {
                setOrderInformation(builder, ref data);

                var alternatepaymentMethod = (AlternativePaymentMethod)builder.PaymentMethod;

                var notifications = new JsonDoc()
                                    .Set("return_url", alternatepaymentMethod?.ReturnUrl)
                                    .Set("status_url", alternatepaymentMethod?.StatusUpdateUrl)
                                    .Set("cancel_url", alternatepaymentMethod?.CancelUrl);

                data.Set("notifications", notifications);
            }

            // stored credential
            if (builder.StoredCredential != null)
            {
                data.Set("initiator", EnumConverter.GetMapping(Target.GP_API, builder.StoredCredential.Initiator));
                var storedCredential = new JsonDoc()
                                       .Set("model", EnumConverter.GetMapping(Target.GP_API, builder.StoredCredential.Type))
                                       .Set("reason", EnumConverter.GetMapping(Target.GP_API, builder.StoredCredential.Reason))
                                       .Set("sequence", EnumConverter.GetMapping(Target.GP_API, builder.StoredCredential.Sequence));
                data.Set("stored_credential", storedCredential);
            }

            return(new GpApiRequest {
                Verb = HttpMethod.Post,
                Endpoint = $"{merchantUrl}/transactions",
                RequestBody = data.ToString(),
            });
        }