public void MapResponseTest() { // 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\":{\"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?.SequenceNumber); Assert.AreEqual(doc.Get("action").GetValue <string>("result_code"), transaction.ResponseCode); Assert.AreEqual(doc.GetValue <string>("id"), transaction.Token); if (doc.Has("payment_method")) { 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); } if (doc.Has("card")) { Assert.AreEqual(doc.Get("card")?.GetValue <string>("number"), transaction.CardNumber); Assert.AreEqual(doc.Get("card")?.GetValue <string>("brand"), transaction.CardType); Assert.AreEqual(doc.Get("card")?.GetValue <int>("expiry_month"), transaction.CardExpMonth); Assert.AreEqual(doc.Get("card")?.GetValue <int>("expiry_year"), transaction.CardExpYear); } }
public static DccRateData MapDccInfo(JsonDoc response) { var currencyConversion = response; if ((!response.Get("action").GetValue("type").Equals("RATE_LOOKUP")) && !response.Has("currency_conversion")) { return(null); } if (response.Has("currency_conversion")) { currencyConversion = response.Get("currency_conversion"); } return(new DccRateData { CardHolderCurrency = currencyConversion.GetValue <string>("payer_currency") ?? null, CardHolderAmount = currencyConversion.GetValue <string>("payer_amount").ToAmount() ?? null, CardHolderRate = currencyConversion.GetValue <string>("exchange_rate").ToDecimal() ?? null, MerchantCurrency = currencyConversion.GetValue <string>("currency") ?? null, MerchantAmount = currencyConversion.GetValue <string>("amount").ToAmount() ?? null, MarginRatePercentage = currencyConversion.GetValue <string>("margin_rate_percentage") ?? null, ExchangeRateSourceName = currencyConversion.GetValue <string>("exchange_rate_source") ?? null, CommissionPercentage = currencyConversion.GetValue <string>("commission_percentage") ?? null, ExchangeRateSourceTimestamp = currencyConversion.GetValue <DateTime?>("exchange_rate_time_created", DateConverter), DccId = currencyConversion.GetValue <string>("id") ?? null }); }
internal virtual void MapResponseValues(JsonDoc doc) { Token = doc.GetValue <string>("token"); Type = doc.GetValue <string>("type"); AppId = doc.GetValue <string>("app_id"); AppName = doc.GetValue <string>("app_name"); TimeCreated = doc.GetValue <DateTime>("time_created"); SecondsToExpire = doc.GetValue <int>("seconds_to_expire"); Email = doc.GetValue <string>("email"); if (doc.Has("scope")) { JsonDoc scope = doc.Get("scope"); MerchantId = scope.GetValue <string>("merchant_id"); MerchantName = scope.GetValue <string>("merchant_name"); if (scope.Has("accounts")) { var accounts = new List <GpApiAccount>(); foreach (JsonDoc account in scope.GetArray <JsonDoc>("accounts")) { accounts.Add(new GpApiAccount { Id = account.GetValue <string>("id"), Name = account.GetValue <string>("name"), }); } Accounts = accounts.ToArray(); } } }
public static PayLinkSummary MapPayLinkSummary(JsonDoc doc) { var summary = new PayLinkSummary(); summary.Id = doc.GetValue <string>("id"); summary.MerchantId = doc.GetValue <string>("merchant_id"); summary.MerchantName = doc.GetValue <string>("merchant_name"); summary.AccountId = doc.GetValue <string>("account_id"); summary.AccountName = doc.GetValue <string>("account_name"); summary.Url = doc.GetValue <string>("url"); summary.Status = GetPayLinkStatus(doc); summary.Type = GetPayLinkType(doc); summary.AllowedPaymentMethods = GetAllowedPaymentMethods(doc); summary.UsageMode = GetPaymentMethodUsageMode(doc); summary.UsageCount = doc.GetValue <string>("usage_count"); summary.Reference = doc.GetValue <string>("reference"); summary.Name = doc.GetValue <string>("name"); summary.Description = doc.GetValue <string>("description"); summary.Shippable = doc.GetValue <string>("shippable"); summary.ViewedCount = doc.GetValue <string>("viewed_count"); summary.ExpirationDate = doc.GetValue <DateTime?>("expiration_date", DateConverter); summary.Images = doc.GetArray <string>("images").ToArray();//GetImages(doc); //ToDo if (doc.Has("transactions")) { summary.Transactions = new List <TransactionSummary>(); foreach (var transaction in doc.GetArray <JsonDoc>("transactions") ?? Enumerable.Empty <JsonDoc>()) { summary.Transactions.Add(CreateTransactionSummary(transaction)); } } return(summary); }
private static PayLinkType?GetPayLinkType(JsonDoc doc) { if (doc.Has("type")) { return((PayLinkType)Enum.Parse(typeof(PayLinkType), doc.GetValue <string>("type").ToUpper())); } return(null); }
private static bool?GetIsShippable(JsonDoc doc) { if (doc.Has("shippable")) { return(doc.GetValue <string>("shippable").ToUpper() == "TRUE" ? true : false); } return(null); }
private static PayLinkStatus?GetPayLinkStatus(JsonDoc doc) { if (doc.Has("status")) { return((PayLinkStatus)Enum.Parse(typeof(PayLinkStatus), doc.GetValue <string>("status"))); } return(null); }
public static 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 <string>("amount").ToAmount(); 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"); if (json.Has("payment_method")) { JsonDoc paymentMethod = json.Get("payment_method"); transaction.AuthorizationCode = paymentMethod.GetValue <string>("result"); if (paymentMethod.Has("card")) { JsonDoc card = paymentMethod.Get("card"); transaction.CardType = card.GetValue <string>("brand"); transaction.CardLast4 = card.GetValue <string>("masked_number_last4"); transaction.CvnResponseMessage = card.GetValue <string>("cvv_result"); } } if (json.Has("card")) { JsonDoc card = json.Get("card"); transaction.CardNumber = card.GetValue <string>("number"); transaction.CardType = card.GetValue <string>("brand"); transaction.CardExpMonth = card.GetValue <int>("expiry_month"); transaction.CardExpYear = card.GetValue <int>("expiry_year"); } } return(transaction); }
private static PaymentMethodUsageMode?GetPaymentMethodUsageMode(JsonDoc json) { if (json.Has("usage_mode")) { if (json.GetValue <string>("usage_mode").Equals(EnumConverter.GetMapping(Target.GP_API, PaymentMethodUsageMode.Single))) { return(PaymentMethodUsageMode.Single); } else if (json.GetValue <string>("usage_mode").Equals(EnumConverter.GetMapping(Target.GP_API, PaymentMethodUsageMode.Multiple))) { return(PaymentMethodUsageMode.Multiple); } } return(null); }
private static BankPaymentType?GetBankPaymentType(JsonDoc response) { if (response.Has("payment_type")) { if (BankPaymentType.FASTERPAYMENTS.ToString().ToUpper().Equals(response.GetValue <string>("payment_type").ToUpper())) { return(BankPaymentType.FASTERPAYMENTS); } else if (BankPaymentType.SEPA.ToString().ToUpper().Equals(response.GetValue <string>("payment_type").ToUpper())) { return(BankPaymentType.SEPA); } } return(null); }
private static List <PaymentMethodName> GetAllowedPaymentMethods(JsonDoc doc) { List <PaymentMethodName> List = null; if (doc.Has("allowed_payment_methods")) { List = new List <PaymentMethodName>(); foreach (var item in doc.GetArray <string>("allowed_payment_methods")) { PaymentMethodName methodName = EnumConverter.FromMapping <PaymentMethodName>(Target.GP_API, item); List.Add(methodName); } } return(List); }
public static bool AreEqual(JsonDoc expected, JsonDoc compare) { // initial compare foreach (var key in expected.Keys) { if (!compare.Has(key)) { return(false); } var expObj = expected.GetValue(key); var compObj = compare.GetValue(key); if (compObj == null || compObj.GetType() != expObj.GetType()) { return(false); } if (expObj is JsonDoc) { if (!AreEqual((JsonDoc)expObj, (JsonDoc)compObj)) { return(false); } } else { if (!expObj.Equals(compObj)) { return(false); } } } // extra property check foreach (var key in compare.Keys) { if (!expected.Has(key)) { return(false); } } return(true); }
protected override void MapResponse(JsonDoc response) { base.MapResponse(response); Assignments = new ShiftAssignments(); // if we have a row, then it's an array if (response.Has("row")) { foreach (var row in response.GetEnumerator("row")) { AddAssignment(row); } } else { AddAssignment(response); } }
private Customer HydrateCustomer(JsonDoc response) { var customer = new Customer { Key = response.GetValue <string>("customerKey"), Id = response.GetValue <string>("customerIdentifier"), FirstName = response.GetValue <string>("firstName"), LastName = response.GetValue <string>("lastName"), Company = response.GetValue <string>("company"), Status = response.GetValue <string>("customerStatus"), Title = response.GetValue <string>("title"), Department = response.GetValue <string>("department"), Email = response.GetValue <string>("primaryEmail"), HomePhone = response.GetValue <string>("phoneDay"), WorkPhone = response.GetValue <string>("phoneEvening"), MobilePhone = response.GetValue <string>("phoneMobile"), Fax = response.GetValue <string>("fax"), Address = new Address { StreetAddress1 = response.GetValue <string>("addressLine1"), StreetAddress2 = response.GetValue <string>("addressLine2"), City = response.GetValue <string>("city"), Province = response.GetValue <string>("stateProvince"), PostalCode = response.GetValue <string>("zipPostalCode"), Country = response.GetValue <string>("country") } }; if (response.Has("paymentMethods")) { customer.PaymentMethods = new List <RecurringPaymentMethod>(); foreach (JsonDoc paymentResponse in response.GetEnumerator("paymentMethods")) { var paymentMethod = HydratePaymentMethod(paymentResponse); if (paymentMethod != null) { customer.PaymentMethods.Add(paymentMethod); } } } return(customer); }
internal override void FromJson(JsonDoc doc, PayrollEncoder encoder) { base.FromJson(doc, encoder); if (Description == null) { Description = doc.GetValue <string>("LaborFieldTitle"); } if (doc.Has("laborfieldLookups")) { Lookup = new List <LaborFieldLookup>(); foreach (var lookup in doc.GetEnumerator("laborfieldLookups")) { Lookup.Add(new LaborFieldLookup { Description = lookup.GetValue <string>("laborFieldDescription"), Value = lookup.GetValue <string>("laborFieldValue") }); } } }
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); }
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); }
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); }
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(), }); }
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)); }
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); }
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); }
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(), }); }