Example #1
0
        public void CreateIPizzaAuthRequest_Verify_4012_Request_Parameters()
        {
            BankRequest bankRequest = _banklinkApi.CreateIPizzaAuthRequest(new IPizzaAuthRequestParams
            {
                Language             = "EST",
                RequestStartDateTime = DateTime.ParseExact("2015-04-04T22:23:30+0300", "yyyy-MM-ddTHH:mm:sszz00", CultureInfo.InvariantCulture),
                RequestEncoding      = "utf-8",
                BankId    = "GENIPIZZA",
                RequestId = "1428175410690",
                ReturnUrl = "http://localhost:30535/Home/AcceptAuth",
                Nonce     = "9a3d6bd2-36d4-49b0-ae44-680c0281f39f"
            });

            Assert.That(bankRequest.RequestUrl, Is.EqualTo("http://localhost:8080/banklink/ipizzaauth"));

            bankRequest.AssertFieldValueEqualTo("VK_SERVICE", "4012");
            bankRequest.AssertFieldValueEqualTo("VK_VERSION", "008");
            bankRequest.AssertFieldValueEqualTo("VK_SND_ID", "uid100010");
            bankRequest.AssertFieldValueEqualTo("VK_REC_ID", "GENIPIZZA");
            bankRequest.AssertFieldValueEqualTo("VK_NONCE", "9a3d6bd2-36d4-49b0-ae44-680c0281f39f");
            bankRequest.AssertFieldValueEqualTo("VK_RETURN", "http://localhost:30535/Home/AcceptAuth");
            bankRequest.AssertFieldValueEqualTo("VK_DATETIME", "2015-04-04T22:23:30+0300");
            bankRequest.AssertFieldValueEqualTo("VK_RID", "1428175410690");
            bankRequest.AssertFieldValueEqualTo("VK_MAC", "H0r2Xoa0vzvylLxsWAphevA15rZpQ2buzzZlf/VFexaYKmXzZHWZnHCa7Pwf3VZ8ZoScFwVzlQAW5LJLlElPsliWaiovKZrVs4WCXTkP7Cd4jqRfDh4YwXCL+fISn/D9xTi/J3v17vKek7BbTVicRUGqf0ynh+DjgAVezaoPbfZ53ppaLESoqK3RF7O+HqphOxDwM8vO8g8+QiTs7dxJzru7SJlPCmLO1idc9TCoY+e80+fHCo2+zzz2cZu2iM48C6Ahk0tZ06Sw83f/UOhOxNJL6Ar0K9FgNCGBSN+NVQ0SPLg+0ubZ2DA16QAUjYdwYQSYhA+KF8B2ElN74eYvDw==");
            bankRequest.AssertFieldValueEqualTo("VK_ENCODING", "utf-8");
            bankRequest.AssertFieldValueEqualTo("VK_LANG", "EST");
        }
Example #2
0
        public BankResponse processPayment(BankRequest request)
        {
            var seed          = _randomSeed.Generate();
            var transactionId = new DateTimeOffset().ToUnixTimeMilliseconds().ToString();

            // very dangerous, don't use it on production :D
            if (seed < 7 || request.CardNumber == "0000-0000-0000-0000")
            {
                return(new BankResponse {
                    id = transactionId,
                    successful = true,
                    message = "successful transaction",
                    statusCode = 1
                });
            }

            if (seed < 9)
            {
                return(new BankResponse {
                    id = transactionId,
                    successful = false,
                    message = "not enough credit to perform transaction",
                    statusCode = 3
                });
            }

            throw new System.Exception("Bank Service Unavailable");
        }
Example #3
0
        public async Task ShouldSuccessIfBankAuthorizeAsync()
        {
            var bank = new Mock <IBankClient>();
            var repo = new Mock <IPaymentRepository>();

            var request = ValidPaymentRequest.Create(new PaymentRequest(
                                                         cardNumber: "0000-0000-0000-0000",
                                                         expiry: new DateTimeOffset(2020, 01, 01, 0, 0, 0, TimeSpan.Zero),
                                                         amount: 100,
                                                         currency: "USD",
                                                         cvv: "000")).Value;

            var bankRequest = new BankRequest("data");

            bank.Setup(m => m.CreateBankRequestAsync(
                           It.Is <ValidPaymentRequest>(d => d.CardNumber == request.CardNumber)))
            .ReturnsAsync(bankRequest);

            bank.Setup(m => m.AuthorizeAsync(
                           It.Is <BankRequest>(r => r.Data == bankRequest.Data)))
            .ReturnsAsync(Result <BankAuthorizationId> .CreateSuccess(new BankAuthorizationId("Id")));

            var sut    = new PaymentProcessing(bank.Object, repo.Object);
            var actual = await sut.ProcessAsync(request);

            Assert.True(actual.IsSuccess);
        }
Example #4
0
        public void Post()
        {
            //Arrange
            IBankRequest bank_request = new BankRequest();

            IApiClient client = new MockAPIClient();

            IPaymentResponse res = new PaymentResponse();

            IHttpContextAccessor context = MockHttpContext.GetHttpContext("/", "localhost");
            PaymentRequest       request = new PaymentRequest
            {
                cardNo   = "5356492507012290",
                expiry   = "03/18",
                amount   = 50,
                currency = "USD",
                cvv      = 987
            };
            PaymentController controller = new PaymentController(logger);

            //Act
            controller.Post(request, bank_request, client, res, context);
            //Assert
            Assert.IsTrue(PaymentController._payments.Count > 0);
        }
Example #5
0
        public async Task <ProcessResponse> ProcessPaymentAsync(ProcessRequest processRequest)
        {
            var paymentId   = Guid.NewGuid().ToString();
            var bankRequest = new BankRequest(GetBank(processRequest.CardNo), processRequest.CardNo, processRequest.Amount);

            var bankResponse = await _bankIntegration.SendtoAcquirerAsync(bankRequest);

            var dbResponse = await _operations.AddPaymentAsync(processRequest, bankResponse, paymentId);

            if (!dbResponse.Success)
            {
                _logger.LogError("Failed to log payment to databse for Payment Id {PaymentId}", paymentId);
            }

            if (bankResponse.Success)
            {
                return(new ProcessResponse
                {
                    Success = true,
                    PaymentId = paymentId
                });
            }

            _logger.LogWarning("Acquirer returned error for Payment Id {PaymentId}", paymentId);
            return(new ProcessResponse
            {
                Success = false,
                ErrorMessage = bankResponse.Reason,
                Message = "Something went wrong with transaction, please contact card issuer.",
                PaymentId = paymentId
            });
        }
Example #6
0
        public void CreateEstcardPaymentRequest_Verify_Payment_Request_Parameters()
        {
            BankRequest bankRequest = _banklinkApi.CreateEstcardPaymentRequest(new EstcardPaymentRequestParams
            {
                AmountInCents       = 1336,
                ReturnUrl           = "http://localhost:8080/project/mJltvgDF1boyOPpL?payment_action=success",
                TransactionDateTime = DateTime.ParseExact("20140217154349", "yyyyMMddHHmmss", CultureInfo.InvariantCulture),
                Language            = "en",
                RequestEncoding     = "utf-8",
                TransactionNr       = 1392644629
            });

            Assert.AreEqual("http://localhost:8080/banklink/ec", bankRequest.RequestUrl);

            bankRequest.AssertFieldValueEqualTo("action", "gaf");
            bankRequest.AssertFieldValueEqualTo("ver", "004");
            bankRequest.AssertFieldValueEqualTo("id", "uid100049");
            bankRequest.AssertFieldValueEqualTo("ecuno", "1392644629");
            bankRequest.AssertFieldValueEqualTo("eamount", "1336");
            bankRequest.AssertFieldValueEqualTo("cur", "EUR");
            bankRequest.AssertFieldValueEqualTo("datetime", "20140217154349");
            bankRequest.AssertFieldValueEqualTo("feedBackUrl", "http://localhost:8080/project/mJltvgDF1boyOPpL?payment_action=success");
            bankRequest.AssertFieldValueEqualTo("delivery", "S");
            bankRequest.AssertFieldValueEqualTo("charEncoding", "utf-8");
            bankRequest.AssertFieldValueEqualTo("mac", "6E519E71A0403F1A528A4433D89CDEC413B8018A5471E98E0224AD9135C4AA9E3AF6C4635E06CD855E9CEAA7672FB14CA25E542DFEC83840C2D35D078CF7C02F55CEF1ED73F462DD404E141E38E3877ECA287E751469EBD1C20F4E35E77F4751F99688421A5E909D6CBD7208D4F1EAA8BC7F598ACFFAC11D8B7343B0FED592906E37D160AB4A5C3E263459D1FAFD849E242FC2BDF7F9450AA030D1DF1A1A836E64FBA3B2607C030DC4F4976249ED195D578A3DB16FB65D4C158F64A4215F4C150EA6B51DC32164DDE29B61D0FA0F711B731D11B3FB37AAF8D423D871C1122F0AAF11781F4CC078C39EEDE5DD56C14C4F651D7F347C3FF7405C5EAD074A4EB51A");
        }
Example #7
0
        public void CreateIPizzaPaymentRequest_Verify_1012_Request_Parameters()
        {
            BankRequest bankRequest = _banklinkApi.CreateIPizzaPaymentRequest(new IPizzaPaymentRequestParams
            {
                ErrorReturnUrl         = "http://localhost:30535/Home/AcceptPayment",
                Amount                 = 10.15M,
                PaymentMessage         = "Shut up and take my $$$!",
                SuccessReturnUrl       = "http://localhost:30535/Home/AcceptPayment",
                Stamp                  = "74525",
                Currency               = "EUR",
                PaymentReferenceNumber = "",
                Language               = "EST",
                RequestStartDateTime   = DateTime.ParseExact("2015-04-04T23:17:34+0300", "yyyy-MM-ddTHH:mm:sszz00", CultureInfo.InvariantCulture),
                RequestEncoding        = "UTF-8",
                BankId                 = "GENIPIZZA"
            });

            Assert.That(bankRequest.RequestUrl, Is.EqualTo("http://localhost:8080/banklink/ipizzapayment"));

            bankRequest.AssertFieldValueEqualTo("VK_SERVICE", "1012");
            bankRequest.AssertFieldValueEqualTo("VK_VERSION", "008");
            bankRequest.AssertFieldValueEqualTo("VK_SND_ID", "uid100010");
            bankRequest.AssertFieldValueEqualTo("VK_STAMP", "74525");
            bankRequest.AssertFieldValueEqualTo("VK_AMOUNT", "10.15");
            bankRequest.AssertFieldValueEqualTo("VK_CURR", "EUR");
            bankRequest.AssertFieldValueEqualTo("VK_REF", "");
            bankRequest.AssertFieldValueEqualTo("VK_MSG", "Shut up and take my $$$!");
            bankRequest.AssertFieldValueEqualTo("VK_RETURN", "http://localhost:30535/Home/AcceptPayment");
            bankRequest.AssertFieldValueEqualTo("VK_CANCEL", "http://localhost:30535/Home/AcceptPayment");
            bankRequest.AssertFieldValueEqualTo("VK_DATETIME", "2015-04-04T23:17:34+0300");
            bankRequest.AssertFieldValueEqualTo("VK_MAC", "L1R5dsif+0Bba2NMZSN0f8uvyyLvtGd6JDIdOQ4/tK5bwLMHss5cZgFmKrUC8pXlmOtMYXrd+sh3WdqTo5W2K1N/Vwq6iPM14J56ZlJ24hM9iRS8KeCIiWkXgAnWpRtrXvvZWnLYkTdZrTiwZajml6hbkxiQY0UPSkQ/CNU3Re1mSjNW2ys0AJJ7RuoGmXbY5htubEcEiKsHFC76q1Ije+OrKlVJPCSLMbfAPe8Wc7LEP5OTowJ/O6MxocFE0A4U5ks5bSc3QO2XRZaIy6FkCIjZABhABICBmyuabfsWaHYAuuN7OjIvfYaTTryaAhY1gfWpLs1z5ForwOmGT5bG4A==");
            bankRequest.AssertFieldValueEqualTo("VK_ENCODING", "UTF-8");
            bankRequest.AssertFieldValueEqualTo("VK_LANG", "EST");
        }
Example #8
0
        public IActionResult Update([FromBody] BankRequest request)
        {
            var info    = _mapper.Map <BankInfo>(request);
            var success = _BankService.Update(info).Result;

            return(Ok(success));
        }
Example #9
0
        public void CreateIPizzaAuthRequest_Verify_4011_Request_Parameters()
        {
            BankRequest bankRequest = _banklinkApi.CreateIPizzaAuthRequest(new IPizzaAuthRequestParams
            {
                Language             = "EST",
                RequestStartDateTime = DateTime.ParseExact("2015-04-04T22:23:30+0300", "yyyy-MM-ddTHH:mm:sszz00", CultureInfo.InvariantCulture),
                RequestEncoding      = "utf-8",
                BankId             = "GENIPIZZA",
                ExpectedReturnCode = "3012",
                RequestId          = "1428175410690",
                ReturnUrl          = "http://localhost:8080/project/6rGPnXJ7cvstStKx?auth_action=success"
            });

            Assert.AreEqual("http://localhost:8080/banklink/ipizzaauth", bankRequest.RequestUrl);

            bankRequest.AssertFieldValueEqualTo("VK_SERVICE", "4011");
            bankRequest.AssertFieldValueEqualTo("VK_VERSION", "008");
            bankRequest.AssertFieldValueEqualTo("VK_SND_ID", "uid100010");
            bankRequest.AssertFieldValueEqualTo("VK_REPLY", "3012");
            bankRequest.AssertFieldValueEqualTo("VK_RETURN", "http://localhost:8080/project/6rGPnXJ7cvstStKx?auth_action=success");
            bankRequest.AssertFieldValueEqualTo("VK_DATETIME", "2015-04-04T22:23:30+0300");
            bankRequest.AssertFieldValueEqualTo("VK_RID", "1428175410690");
            bankRequest.AssertFieldValueEqualTo("VK_MAC", "SglHiOfR/FWRSnImNGBqmt139gmKxWeQQoSd3NoLJ5oSqSykT704oTZgZteJn8tDRSwhQEO5d7x1CX3wCn2Huzau6wZx/7k1nqH4s11TF9X6tw5DNHpgCId4li9RGH/v7j2cUBz5835ZZZ6gPNFZ6NCQdCeYD1Qr15Mq4wduotsAKznD/TWna5geQgfSbvPKrRT2yKCFdO+k9WujHD/OqqIQ5HNJy+q2k/8+5zb+stHr84FnoR/V2+prKhCM+yyJR3W85t7RiUQa+DgooZ2lITJj1SeNVxxilNcclkuwe7Jm/+CXrb2IEF1bXYkTO4W4dPDq4u7ofhJjXvc7c2EThQ==");
            bankRequest.AssertFieldValueEqualTo("VK_ENCODING", "utf-8");
            bankRequest.AssertFieldValueEqualTo("VK_LANG", "EST");
        }
Example #10
0
        public async Task <PaymentResponse> RequestPayment(PaymentRequest model)
        {
            var result = model.Validate();

            if (!result.IsValid)
            {
                var errors       = result.Errors.Select(e => e.ErrorMessage);
                var errorMessage = string.Join(", ", errors);
                throw new ArgumentException("Payment Request is Invalid: " + errorMessage);
            }

            var merchant = await _merchantRepo.GetMerchantById(model.MerchantId.Value);

            if (merchant == null)
            {
                throw new NotFoundException("Invalid Merchant Id");
            }

            var payment = new Payment
            {
                CardNumber     = _encryption.Mask(model.CardNumber),
                Cvv            = model.CardCvv,
                CreatedOn      = DateTime.UtcNow,
                CardHolderName = model.CardHolderName,
                ExpiryMonth    = model.ExpiryMonth,
                ExpiryYear     = model.ExpiryYear,
                Amount         = model.Amount,
                Currency       = model.Currency,
                Status         = PaymentStatus.Pending,
                MerchantId     = merchant.MerchantId
            };

            await _paymentRepository.Create(payment);

            //Call Bank
            var bankRequest = new BankRequest
            {
                CardNumber     = model.CardNumber,
                CardCvv        = model.CardCvv,
                CardHolderName = model.CardHolderName,
                ExpiryMonth    = model.ExpiryMonth,
                ExpiryYear     = model.ExpiryYear,
                Amount         = model.Amount,
            };

            //Make call to bank
            var response = await _bankClient.ProcessPayment(bankRequest);

            payment.Reference = response.Reference;
            payment.Status    = response.Status;

            await _paymentRepository.Update(payment);

            return(new PaymentResponse
            {
                Status = payment.Status,
                Reference = payment.Reference
            });
        }
Example #11
0
        public static void AssertFieldValueEqualTo(this BankRequest bankRequest, string fieldName, string expectedFieldValue)
        {
            BankMessageField bankMessageField = bankRequest
                                                .PostParameters
                                                .First(field => field.FieldName == fieldName);

            Assert.That(bankMessageField.Value, Is.EqualTo(expectedFieldValue));
        }
        public BankResponse Post([FromBody] BankRequest request)
        {
            var random = new Random();

            return(new BankResponse
            {
                Id = Guid.NewGuid(),
                PaymentStatus = (PaymentStatusCode)random.Next(0, 2)
            });
        }
Example #13
0
        public async Task <Bank?> GetBank(string?accessToken = null)
        {
            var request = new BankRequest(accessToken);

            using var response = await _http.SendAsync(request).ConfigureAwait(false);

            response.EnsureSuccessStatusCode();
            var json = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            return(JsonConvert.DeserializeObject <Bank>(json, Json.DefaultJsonSerializerSettings));
        }
Example #14
0
 public Task <BankResponse> RequestPaymentAsync(BankRequest request)
 {
     return(Task.FromResult(
                new BankResponse(
                    request.Id,
                    "Stark Bank",
                    true,
                    200,
                    _rng.Next().ToString("D6", CultureInfo.InvariantCulture),
                    "Payment Accepted")));
 }
Example #15
0
        public ActionResult BankPayment(string bankId)
        {
            BankRequest request = _banklinkApi.CreateIPizzaPaymentRequest(new IPizzaPaymentRequestParams
            {
                Amount           = 10.15M,
                BankId           = bankId,
                Stamp            = new Random((int)DateTime.Now.Ticks).Next(1234567).ToString(),
                ErrorReturnUrl   = Url.Action("AcceptPayment", "Home", new { }, this.Request.Url.Scheme),
                SuccessReturnUrl = Url.Action("AcceptPayment", "Home", new{}, this.Request.Url.Scheme),
                PaymentMessage   = "Shut up and take my $$$!",
            });

            return(View("BankRequest", request));
        }
Example #16
0
        public async Task <BankResponse> SendtoAcquirerAsync(BankRequest bankRequest)
        {
            var url = _configurationReader.Read(bankRequest.Bank).Url;

            var httpClient = _httpClientFactory.CreateClient();

            var result = await httpClient.PostAsJsonAsync(url, bankRequest);

            var response = JsonConvert.DeserializeObject <BankResponse>(await result.Content.ReadAsStringAsync());

            response.TransactionId = Guid.NewGuid().ToString();

            return(response);
        }
Example #17
0
        public async Task <BankResponse> PostBankRequestAsync(BankRequest bankRequest)
        {
            var client = _httpClientFactory.CreateClient("BankA");

            var json = JsonConvert.SerializeObject(bankRequest);
            var data = new StringContent(json, Encoding.UTF8, "application/json");

            var response = await client.PostAsync("api/payment", data);

            var responseString = await response.Content.ReadAsStringAsync();

            var bankResponse = JsonConvert.DeserializeObject <BankResponse>(responseString);

            return(bankResponse);
        }
Example #18
0
        public ActionResult BankAuth(string bankId)
        {
            BankRequest request = _banklinkApi.CreateIPizzaAuthRequest(new IPizzaAuthRequestParams
            {
                Language             = "EST",
                RequestStartDateTime = DateTime.ParseExact("2015-04-04T22:23:30+0300", "yyyy-MM-ddTHH:mm:sszz00", CultureInfo.InvariantCulture),
                RequestEncoding      = "utf-8",
                BankId    = "GENIPIZZA",
                RequestId = "1428175410690",
                ReturnUrl = Url.Action("AcceptAuth", "Home", new { }, this.Request.Url.Scheme),
                Nonce     = Guid.NewGuid().ToString()
            });

            return(View("BankRequest", request));
        }
Example #19
0
        public async Task InitializeAsync()
        {
            await using var container = new Container();
            var http    = container.Resolve <IHttpClientFactory>().CreateClient("GW2SDK");
            var request = new BankRequest(ConfigurationManager.Instance.ApiKeyFull);

            using var response = await http.SendAsync(request);

            using var responseReader = new StreamReader(await response.Content.ReadAsStreamAsync());
            using var jsonReader     = new JsonTextReader(responseReader);
            response.EnsureSuccessStatusCode();

            var array = await JArray.LoadAsync(jsonReader);

            Bank = array.ToString(Formatting.None);
        }
Example #20
0
        public async Task <BankResponse> ProcessPayment(BankRequest bankRequest)
        {
            var status  = PaymentStatus.Success;
            var message = string.Empty;

            switch (bankRequest.CardNumber)
            {
            case "1234 1234 1234 1234":
                status  = PaymentStatus.Failure;
                message = "Insufficient Funds";
                break;
                // ......
            }

            return(await Task.FromResult(
                       new BankResponse
            {
                Reference = GenerateReference(),
                Status = status,
                Message = message
            }));
        }
Example #21
0
        /// <summary>
        /// Gets the banks.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        public BankResponse GetBanks(BankRequest request)
        {
            var response = new BankResponse();

            if (request.LoadOptions.Contains("Banks"))
            {
                if (request.LoadOptions.Contains("IsActive"))
                {
                    response.Banks = BankDao.GetBanksByActive(true);
                }
                else
                {
                    response.Banks = BankDao.GetBanks();
                }
            }
            if (request.LoadOptions.Contains("Bank"))
            {
                response.Bank = BankDao.GetBank(request.BankId);
            }

            return(response);
        }
Example #22
0
        public void CreateIPizzaPaymentRequest_Verify_1011_Request_Parameters()
        {
            BankRequest bankRequest = _banklinkApi.CreateIPizzaPaymentRequest(new IPizzaPaymentRequestParams
            {
                ErrorReturnUrl         = "http://localhost:8080/project/6rGPnXJ7cvstStKx?payment_action=cancel",
                Amount                 = 150M,
                PaymentMessage         = "Torso Tiger",
                SuccessReturnUrl       = "http://localhost:8080/project/6rGPnXJ7cvstStKx?payment_action=success",
                RecipientAccountNumber = "EE871600161234567892",
                RecipientName          = "ÕIE MÄGER",
                Stamp    = "12345",
                Currency = "EUR",
                PaymentReferenceNumber = "1234561",
                Language             = "EST",
                RequestStartDateTime = DateTime.ParseExact("2015-04-04T22:58:16+0300", "yyyy-MM-ddTHH:mm:sszz00", CultureInfo.InvariantCulture),
                RequestEncoding      = "UTF-8",
                BankId = "GENIPIZZA"
            });

            Assert.That(bankRequest.RequestUrl, Is.EqualTo("http://localhost:8080/banklink/ipizzapayment"));

            bankRequest.AssertFieldValueEqualTo("VK_SERVICE", "1011");
            bankRequest.AssertFieldValueEqualTo("VK_VERSION", "008");
            bankRequest.AssertFieldValueEqualTo("VK_SND_ID", "uid100010");
            bankRequest.AssertFieldValueEqualTo("VK_STAMP", "12345");
            bankRequest.AssertFieldValueEqualTo("VK_AMOUNT", "150");
            bankRequest.AssertFieldValueEqualTo("VK_CURR", "EUR");
            bankRequest.AssertFieldValueEqualTo("VK_ACC", "EE871600161234567892");
            bankRequest.AssertFieldValueEqualTo("VK_NAME", "ÕIE MÄGER");
            bankRequest.AssertFieldValueEqualTo("VK_REF", "1234561");
            bankRequest.AssertFieldValueEqualTo("VK_MSG", "Torso Tiger");
            bankRequest.AssertFieldValueEqualTo("VK_RETURN", "http://localhost:8080/project/6rGPnXJ7cvstStKx?payment_action=success");
            bankRequest.AssertFieldValueEqualTo("VK_CANCEL", "http://localhost:8080/project/6rGPnXJ7cvstStKx?payment_action=cancel");
            bankRequest.AssertFieldValueEqualTo("VK_DATETIME", "2015-04-04T22:58:16+0300");
            bankRequest.AssertFieldValueEqualTo("VK_MAC", "N2aCtj20ynyMqirBV77bd/8JpG7yCH6G1W44yKFI7fHdnzgd0zUXZgkhNKOuZB+se0lmj5m+rzzvpkhuPjig3MI0gTE7SLcUAerck8QKr02dd+EQv14OKrw3wZSuuwPUZcH/PvySctKT3kOSO6FFI8ymdww7/CC1xdSAWAOes2wbv68Dtwhy4qQ1pc+jSqFNmNjwgK56BP1D2JBhikATUJxM4b0/GUA0utqkekekqrinElaQRQ8ddN8Jij7t+KPQme1w5xGU48DR4mI+A6nHKAVm+UinbEkRIuoc0sWba9vBvNBSdIAMYv1a3BVpg956Kx0uo1ZTc7veDDi7tFCb9w==");
            bankRequest.AssertFieldValueEqualTo("VK_ENCODING", "UTF-8");
            bankRequest.AssertFieldValueEqualTo("VK_LANG", "EST");
        }
Example #23
0
 public async Task <BankResponse> ProcessPayment(BankRequest bankRequest)
 {
     //Actual real bank call comes here.
     throw new NotImplementedException();
 }
Example #24
0
        static void aMain(string[] args)
        {
            InsuranceWebService insuranceWebService = new InsuranceWebService();
            var insRequest = new InsuranceRequest();
            var mySession  = new SessionRequest();
            var myBank     = new BankRequest();
            var myPolicy   = new PolicyRequest();
            var myClient   = new ClientRequest();
            var myVehicle  = new VehicleRequest();
            var myLoan     = new LoanRequest();

            mySession.Username              = "";
            mySession.AuthenticationKey     = "";
            mySession.Bordereaux            = false;
            mySession.Account               = "";
            mySession.GuaranteeWarrantyDate = new DateTime();
            mySession.PaidByCard            = true;
            mySession.DeliveryDate          = new DateTime();
            mySession.LoanProvided          = false;

            myClient.FirstName   = "";
            myClient.Surname     = "";
            myClient.Title       = "";
            myClient.HouseNumber = "";
            myClient.Address     = "";
            myClient.Postcode    = "";
            myClient.Email       = "";
            myClient.Telephone   = "";
            //Optional
            myClient.DateOfBirth = new DateTime();
            //END Optional
            myClient.IsCompany = false;

            myPolicy.Description  = "";
            myPolicy.Plan         = "";
            myPolicy.GrossPremium = 0;
            myPolicy.Product      = "";
            myPolicy.CoverPeriod  = 0;
            //Optional
            myPolicy.DatePISupplied        = new DateTime();
            myPolicy.ExternalReference     = "";
            myPolicy.DateCustomerConfirmed = new DateTime();
            //END Optional
            myPolicy.PaidByCard = false;

            myVehicle.Make           = "";
            myVehicle.Model          = "";
            myVehicle.Registration   = "";
            myVehicle.Price          = 0;
            myVehicle.Mileage        = 0;
            myVehicle.DateRegistered = new DateTime();
            myVehicle.EngineSize     = 0;
            myVehicle.MOTDate        = new DateTime();
            myVehicle.Fuel           = "";
            myVehicle.NewVehicle     = false;
            myVehicle.Motorcycle     = false;

            myBank.AccountName        = "";
            myBank.AccountNumber      = "";
            myBank.PaperlessDDI       = false;
            myBank.PayeeAddress       = "";
            myBank.PayeeFirstName     = "";
            myBank.PayeeSurname       = "";
            myBank.PayeeHouseNumber   = "";
            myBank.PayeePostcode      = "";
            myBank.PayeeTitle         = "";
            myBank.SortCode           = "";
            myBank.PolicyHolderPaying = false;

            //Optional
            myLoan.Advance        = 0;
            myLoan.AdvanceRentals = 0;
            myLoan.LoanPayment    = 0;
            myLoan.LoanTerm       = 0;
            //END Optional
            myLoan.BorrowerName = "";
            myLoan.Lender       = "";

            insRequest.Session = mySession;
            insRequest.Vehicle = myVehicle;
            insRequest.Client  = myClient;
            insRequest.Policy  = myPolicy;
            insRequest.Bank    = myBank;
            insRequest.Loan    = myLoan;

            var response = insuranceWebService.CreatePolicyByInsuranceRequest(insRequest);


            if (response.Success)
            {
                Console.WriteLine("Success");
            }
            else
            {
                Console.WriteLine("Fail");
            }
            Console.ReadKey();
        }
Example #25
0
        public PaymentResponse Create(CreatePaymentDto createPaymentDto)
        {
            var bankResponse = new BankResponse {
                id         = "",
                successful = false,
                statusCode = 0,
                message    = "this request never made it to the bank",
            };

            var paymentModel = new PaymentModel {
                Issuer          = createPaymentDto.Issuer,
                CardHolder      = createPaymentDto.CardHolder,
                Value           = createPaymentDto.Value,
                Currency        = createPaymentDto.Currency,
                CardNumber      = createPaymentDto.CardNumber,
                ExpiryMonth     = createPaymentDto.ExpiryMonth,
                ExpiryYear      = createPaymentDto.ExpiryYear,
                CCV             = createPaymentDto.CCV,
                transactionDate = System.DateTimeOffset.Now.UtcDateTime,
                response        = bankResponse
            };


            var bankRequest = new BankRequest {
                Issuer      = createPaymentDto.Issuer,
                CardHolder  = createPaymentDto.CardHolder,
                Value       = createPaymentDto.Value,
                Currency    = createPaymentDto.Currency,
                CardNumber  = createPaymentDto.CardNumber,
                ExpiryMonth = createPaymentDto.ExpiryMonth,
                ExpiryYear  = createPaymentDto.ExpiryYear,
                CCV         = createPaymentDto.CCV,
            };

            _paymentModelCollection.InsertOne(paymentModel);

            try {
                bankResponse = _acquiringBank.processPayment(bankRequest);

                paymentModel.response = bankResponse;

                this.Update(paymentModel.Id, paymentModel);
            }  catch (System.Exception ex) {
                var exceptionMetric = new ExceptionMetric {
                    origin    = nameof(PaymentService),
                    exception = new AcquiringBankNotAvailable(ex.Message),
                    time      = new DateTimeOffset().Date,
                    stack     = ex.StackTrace
                };

                _logger.Log <ExceptionMetric>(LogLevel.Error, new EventId {
                }, exceptionMetric, ex);
            }

            paymentModel.CardNumber = this.HideCreditCardNumber(paymentModel.CardNumber);
            paymentModel.CCV        = this.HideCCV();

            return(new PaymentResponse {
                paymentRequest = paymentModel,
                paymentResponse = bankResponse,
            });
        }
Example #26
0
 public Task <Result <BankAuthorizationId> > AuthorizeAsync(BankRequest request) =>
 Task.FromResult(
     Result <BankAuthorizationId> .CreateSuccess(
         new BankAuthorizationId(Guid.NewGuid().ToString("N"))));
Example #27
0
        public async Task We_Are_Able_To_Go_Through_The_Whole_Payment_Process()
        {
            var createPaymentDto = new CreatePaymentDto {
                Issuer      = "amazon-issuer-id",
                CardHolder  = "John Cage",
                Value       = 199.99m,
                Currency    = "Euro",
                CardNumber  = "0000-0000-0000-0000",
                ExpiryMonth = 13,
                ExpiryYear  = 2099,
                CCV         = "12e2",
            };

            var bankResponse = new BankResponse {
                id         = "fake-id",
                successful = true,
                message    = "very nice",
                statusCode = 1
            };

            var paymentModelDocument = new PaymentModel {
                Id          = "mocked-id",
                Issuer      = "amazon-issuer-id",
                CardHolder  = "John Cage",
                Value       = 199.99m,
                Currency    = "Euro",
                CardNumber  = "0000-0000-0000-0000",
                ExpiryMonth = 13,
                ExpiryYear  = 2099,
                CCV         = "12e2",
                response    = bankResponse,
            };

            var bankRequest = new BankRequest {
                Issuer      = "amazon-issuer-id",
                CardHolder  = "John Cage",
                Value       = 199.99m,
                Currency    = "Euro",
                CardNumber  = "0000-0000-0000-0000",
                ExpiryMonth = 13,
                ExpiryYear  = 2099,
                CCV         = "12e2",
            };

            var loggerMock = new Mock <ILoggerService>();

            loggerMock.Setup(logger => logger.Log <ExceptionMetric>(LogLevel.Error, new EventId {
            }, new ExceptionMetric {
            }, null, null));

            var mongoCollectionMock = new Mock <IMongoCollection <PaymentModel> >();

            mongoCollectionMock.Setup(col => col.InsertOne(paymentModelDocument, new InsertOneOptions {
            }, default));
            mongoCollectionMock.Setup(col => col.ReplaceOne("mocked-id", paymentModelDocument, new ReplaceOptions {
            }, default));

            var mockedBank = new Mock <IAcquiringBank>();

            mockedBank.Setup(bank => bank.processPayment(bankRequest)).Returns(bankResponse);

            var paymentService = new PaymentService(mongoCollectionMock.Object, mockedBank.Object, loggerMock.Object);
            var result         = paymentService.Create(createPaymentDto);

            Assert.Equal(2, mongoCollectionMock.Invocations.Count);
            Assert.Equal(1, mockedBank.Invocations.Count);
        }
Example #28
0
        /// <summary>
        /// Sets the banks.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        public BankResponse SetBanks(BankRequest request)
        {
            var response = new BankResponse();

            var bankEntity = request.Bank;

            if (request.Action != PersistType.Delete)
            {
                if (!bankEntity.Validate())
                {
                    foreach (var error in bankEntity.ValidationErrors)
                    {
                        response.Message += error + Environment.NewLine;
                    }
                    response.Acknowledge = AcknowledgeType.Failure;
                    return(response);
                }
            }
            try
            {
                if (request.Action == PersistType.Insert)
                {
                    var banks = BankDao.GetBanksByBankAccount(bankEntity.BankAccount);
                    if (banks.Count > 0)
                    {
                        response.Acknowledge = AcknowledgeType.Failure;
                        response.Message     = @"Mã số tài khoản ngân hàng " + bankEntity.BankAccount + @" đã tồn tại !";
                        return(response);
                    }

                    AutoNumberListDao.UpdateIncreateAutoNumberListByValue("Bank");

                    bankEntity.BankId = BankDao.InsertBank(bankEntity);
                    response.Message  = null;
                }
                else if (request.Action == PersistType.Update)
                {
                    response.Message = BankDao.UpdateBank(bankEntity);
                }
                else
                {
                    var bankForUpdate = BankDao.GetBank(request.BankId);
                    response.Message = BankDao.DeleteBank(bankForUpdate);
                }
            }
            catch (Exception ex)
            {
                response.Acknowledge = AcknowledgeType.Failure;
                response.Message     = ex.Message;
                return(response);
            }
            response.BankId = bankEntity != null ? bankEntity.BankId : 0;
            if (response.Message == null)
            {
                response.Acknowledge  = AcknowledgeType.Success;
                response.RowsAffected = 1;
            }
            else
            {
                response.Acknowledge  = AcknowledgeType.Failure;
                response.RowsAffected = 0;
            }

            return(response);
        }
Example #29
0
        /// <summary>
        /// Получить список запросов к банкам из кода.
        /// </summary>
        /// <returns></returns>
        public IEnumerable <BankRequest> GetBankRequestsFromCode()
        {
            // TODO: получение данных из кода == получение данных из БД.

            // Список банков.
            var bankDataModels = new List <BankRequest>();

            // Установить данные для банков.
            // Переменная часть пути XPath для всех банков.
            var VariablePartOfXpath = "$VARIABLE";

            // Данные для Банка 1.
            // Данные для реализации цикла перебора строк с курсами валют.
            var StartRow1 = 1;
            // Последняя строка задана на 2 больше, чтобы проверить отработку ошибок (должно быть 43).
            var EndRow1 = 43;
            var bank1   = new BankRequest
            {
                Name                   = "National Bank of Georgia",
                SwiftCode              = "BNLNGE22XXX",
                BankCurrency           = "GEL",
                RatesUrlPage           = "https://www.nbg.gov.ge/index.php?m=582&lng=eng",
                NumberDecimalSeparator = ".",
                NumberGroupSeparator   = ",",
                StartXpathRow          = StartRow1,
                EndXpathRow            = EndRow1,
                VariablePartOfXpath    = VariablePartOfXpath
            };

            // Шаблон XPath пути для валюты.
            bank1.XPathes = new CurrencyXPathes()
            {
                TextCode     = "//*[@id='currency_id']/table/tr[$VARIABLE]/td[1]",
                Unit         = "//*[@id='currency_id']/table/tr[$VARIABLE]/td[2]",
                ExchangeRate = "//*[@id='currency_id']/table/tr[$VARIABLE]/td[3]"
            };
            // Задаем команды для обработки текста.
            bank1.UnitScripts = new Dictionary <string, string[]>
            {
                { "GetNumberFromText", Array.Empty <string>() }
            };
            bankDataModels.Add(bank1);


            // Данные для Банка 2.
            var StartRow2 = 2;
            var EndRow2   = 36;
            var bank2     = new BankRequest
            {
                Name                   = "National Bank of Poland",
                SwiftCode              = "NBPLPLPWBAN",
                BankCurrency           = "PLN",
                RatesUrlPage           = "https://www.nbp.pl/homen.aspx?f=/kursy/RatesA.html",
                NumberDecimalSeparator = ".",
                NumberGroupSeparator   = ",",
                StartXpathRow          = StartRow2,
                EndXpathRow            = EndRow2,
                VariablePartOfXpath    = VariablePartOfXpath
            };

            bank2.XPathes = new CurrencyXPathes()
            {
                TextCode     = @"//*[@id=""article""]/table/tr/td/center/table[1]/tr[$VARIABLE]/td[2]",
                Unit         = @"//*[@id=""article""]/table/tr/td/center/table[1]/tr[$VARIABLE]/td[2]",
                ExchangeRate = @"//*[@id=""article""]/table/tr/td/center/table[1]/tr[$VARIABLE]/td[3]"
            };
            // Сформировать число из найденных в строке цифр.
            bank2.UnitScripts = new Dictionary <string, string[]>
            {
                { "GetNumberFromText", Array.Empty <string>() }
            };
            bank2.TextCodeScripts = new Dictionary <string, string[]>
            {
                { "GetTextCodeFromEnd", new string[] { "3" } }
            };
            bankDataModels.Add(bank2);


            // Данные для банка 3.
            var StartRow3 = 2;
            var EndRow3   = 35;
            var bank3     = new BankRequest
            {
                Name                   = "The Central Bank of the Russian Federation",
                SwiftCode              = "CBRFRUMMXXX",
                BankCurrency           = "RUB",
                RatesUrlPage           = "https://www.cbr.ru/eng/currency_base/daily/",
                NumberDecimalSeparator = ".",
                NumberGroupSeparator   = ",",
                StartXpathRow          = StartRow3,
                EndXpathRow            = EndRow3,
                VariablePartOfXpath    = VariablePartOfXpath
            };

            bank3.XPathes = new CurrencyXPathes()
            {
                TextCode     = @"//*[@id='content']/table/tbody/tr[$VARIABLE]/td[2]",
                Unit         = @"//*[@id='content']/table/tbody/tr[$VARIABLE]/td[3]",
                ExchangeRate = @"//*[@id='content']/table/tbody/tr[$VARIABLE]/td[5]"
            };
            bankDataModels.Add(bank3);


            // Данные для банка 4.
            var StartRow4 = 1;
            var EndRow4   = 32;
            var bank4     = new BankRequest
            {
                Name                   = "European Central Bank",
                SwiftCode              = "ECBFDEFFEUM",
                BankCurrency           = "EUR",
                RatesUrlPage           = "https://www.ecb.europa.eu/stats/policy_and_exchange_rates/euro_reference_exchange_rates/html/index.en.html",
                NumberDecimalSeparator = ".",
                NumberGroupSeparator   = ",",
                StartXpathRow          = StartRow4,
                EndXpathRow            = EndRow4,
                VariablePartOfXpath    = VariablePartOfXpath
            };

            bank4.XPathes = new CurrencyXPathes()
            {
                TextCode     = @"//*[@id='ecb-content-col']/main/div/table/tbody/tr[$VARIABLE]/td[1]",
                Unit         = @"//*[@id='ecb-content-col']/main/div/table/tbody/tr[$VARIABLE]/td[1]",
                ExchangeRate = @"//*[@id='ecb-content-col']/main/div/table/tbody/tr[$VARIABLE]/td[3]"
            };
            bank4.UnitScripts = new Dictionary <string, string[]>
            {
                { "GetFixedValue", new string[] { "1" } }
            };
            bankDataModels.Add(bank4);

            return(bankDataModels);
        }
Example #30
0
        public Response CreatePolicyByInsuranceRequest(Dictionary <string, object> parameters)
        {
            try
            {
                var insReq  = new InsuranceRequest();
                var sess    = new SessionRequest();
                var vehicle = new VehicleRequest();
                var client  = new ClientRequest();
                var policy  = new PolicyRequest();
                var bank    = new BankRequest();
                var loan    = new LoanRequest();
                sess.Username              = (String)parameters["username"];
                sess.AuthenticationKey     = (String)parameters["sess.AuthenticationKey"];
                sess.Bordereaux            = (bool)parameters["bordereaux"];
                sess.Account               = (String)parameters["account"];
                sess.GuaranteeWarrantyDate = (DateTime)parameters["guarenteewarrantydate"];
                sess.PaidByCard            = (bool)parameters["paidbycard"];
                sess.DeliveryDate          = (DateTime)parameters["deliverydate"];
                sess.LoanProvided          = (bool)parameters["loanprovided"];

                client.FirstName             = (String)parameters["firstname"];
                client.Surname               = (String)parameters["surname"];
                client.Title                 = (String)parameters["title"];
                client.HouseNumber           = (String)parameters["housenumber"];
                client.Address               = (String)parameters["address"];
                client.Postcode              = (String)parameters["postcode"];
                client.Email                 = (String)parameters["email"];
                client.Telephone             = (String)parameters["telephone"];
                client.IsCompany             = (bool)parameters["iscompany"];
                client.DateOfBirth           = (DateTime)parameters["dateofbirth"];
                policy.Description           = (String)parameters["description"];
                policy.Plan                  = (String)parameters["plan"];
                policy.GrossPremium          = (decimal)parameters["grosspremium"];
                policy.Product               = (String)parameters["product"];
                policy.CoverPeriod           = (int)parameters["coverperiod"];
                policy.DatePISupplied        = (DateTime)parameters["datepisupplied"];
                policy.ExternalReference     = (String)parameters["externalreference"];
                policy.DateCustomerConfirmed = (DateTime)parameters["datecustomerconfirmed"];
                vehicle.Make                 = (String)parameters["make"];
                vehicle.Model                = (String)parameters["model"];
                vehicle.Registration         = (String)parameters["registration"];
                vehicle.Price                = (decimal)parameters["price"];
                vehicle.Mileage              = (int)parameters["mileage"];
                vehicle.DateRegistered       = (DateTime)parameters["dateregistered"];
                vehicle.EngineSize           = (int)parameters["enginesize"];
                vehicle.MOTDate              = (DateTime)parameters["motdate"];
                vehicle.Fuel                 = (String)parameters["fuel"];
                vehicle.NewVehicle           = (bool)parameters["newvehicle"];
                vehicle.Motorcycle           = (bool)parameters["motorcycle"];
                bank.AccountName             = (String)parameters["accountname"];
                bank.AccountNumber           = (String)parameters["accountnumber"];
                bank.PaperlessDDI            = (bool)parameters["paperlessddi"];
                bank.PayeeAddress            = (String)parameters["payeeaddress"];
                bank.PayeeFirstName          = (String)parameters["payeefirstname"];
                bank.PayeeSurname            = (String)parameters["payeesurname"];
                bank.PayeeAddress            = (String)parameters["payeehousenumber"];
                bank.PayeePostcode           = (String)parameters["payeepostcode"];
                bank.PayeeTitle              = (String)parameters["payeetitle"];
                bank.SortCode                = (String)parameters["sortcode"];
                bank.PolicyHolderPaying      = (bool)parameters["policyholderpaying"];
                loan.Advance                 = (decimal)parameters["advance"];
                loan.AdvanceRentals          = (int)parameters["advancerentals"];
                loan.LoanPayment             = (decimal)parameters["loanpayment"];
                loan.LoanTerm                = (int)parameters["loanterm"];
                loan.BorrowerName            = (String)parameters["borrowername"];
                loan.Lender                  = (String)parameters["lender"];
                insReq.Session               = sess;
                insReq.Client                = client;
                insReq.Policy                = policy;
                insReq.Vehicle               = vehicle;
                insReq.Bank                  = bank;
                insReq.Loan                  = loan;

                var response = insuranceWebService.CreatePolicyByInsuranceRequest(insReq);
                return(MethodRespToObject(response));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.InnerException.Message);
                return(null);
            }
        }