Exemple #1
0
        public async Task SavePaymentResponseAsync(CreatePaymentResponse createPaymentResponse)
        {
            if (createPaymentResponse == null)
            {
                createPaymentResponse = new CreatePaymentResponse();
            }

            var jsonSerializedCreatePaymentResponse = JsonConvert.SerializeObject(createPaymentResponse);
            var request = new HttpRequestMessage
            {
                Method     = HttpMethod.Put,
                RequestUri = new Uri($"http://vbase.{this._environmentVariableProvider.Region}.vtex.io/{this._httpContextAccessor.HttpContext.Request.Headers[HEADER_VTEX_ACCOUNT]}/master/buckets/{this._applicationName}/{RESPONSE_BUCKET}/files/{createPaymentResponse.paymentId}"),
                Content    = new StringContent(jsonSerializedCreatePaymentResponse, Encoding.UTF8, APPLICATION_JSON)
            };

            string authToken = this._httpContextAccessor.HttpContext.Request.Headers[HEADER_VTEX_CREDENTIAL];

            if (authToken != null)
            {
                request.Headers.Add(AUTHORIZATION_HEADER_NAME, authToken);
            }

            var response = await _httpClient.SendAsync(request);

            response.EnsureSuccessStatusCode();
        }
        public void OnPost()
        {
            string       nonce       = Request.Form["nonce"];
            IPaymentsApi PaymentsApi = client.PaymentsApi;
            // Every payment you process with the SDK must have a unique idempotency key.
            // If you're unsure whether a particular payment succeeded, you can reattempt
            // it with the same idempotency key without worrying about double charging
            // the buyer.
            string uuid = NewIdempotencyKey();

            // Monetary amounts are specified in the smallest unit of the applicable currency.
            // This amount is in cents. It's also hard-coded for $1.00,
            // which isn't very useful.
            Money amount = new Money.Builder()
                           .Amount(500L)
                           .Currency("USD")
                           .Build();

            // To learn more about splitting payments with additional recipients,
            // see the Payments API documentation on our [developer site]
            // (https://developer.squareup.com/docs/payments-api/overview).
            CreatePaymentRequest createPaymentRequest = new CreatePaymentRequest.Builder(nonce, uuid, amount)
                                                        .Note("From Square Sample Csharp App")
                                                        .Build();

            try
            {
                CreatePaymentResponse response = PaymentsApi.CreatePayment(createPaymentRequest);
                this.ResultMessage = "Payment complete! " + response.Payment.Note;
            }
            catch (ApiException e)
            {
                this.ResultMessage = e.Message;
            }
        }
        public void CreatePaymentTest_FailFor_DateNotSupplied()
        {
            decimal initialBalance         = InMemoryData.CurrentBalance;
            CreatePaymentResponse response = CreatePaymentResponse(10m, DateTime.MinValue);

            AssertForCreatePaymentTests(response, initialBalance, "Amount must be supplied and must be positive number and date must be supplied");
        }
        public async Task <CreatePaymentResponse> Send()
        {
            CreatePaymentResponse response = await SendRequestToServer <CreatePaymentResponse>();

            this.customerToken = response.customerToken;
            return(response);
        }
Exemple #5
0
        static async Task <string> AddPayment(decimal amount, DateTime dateTime)
        {
            Console.WriteLine();
            Console.WriteLine("******add payment test***********");
            Console.WriteLine();
            Uri u = new Uri(baseUrl + "createpayment");

            var response = string.Empty;

            using (var client = new HttpClient())
            {
                CreatePaymentRequest payload = new CreatePaymentRequest();
                payload.Amount      = amount;
                payload.PaymentDate = dateTime;
                HttpResponseMessage res = await client.PostAsJsonAsync(u, payload);

                if (res.IsSuccessStatusCode)
                {
                    CreatePaymentResponse reply = await res.Content.ReadAsAsync <CreatePaymentResponse>();

                    newlyAddedPayments.Add(new KeyValuePair <Guid, string>(reply.Payment.PaymentId, reply.Payment.Status));
                    return(JsonConvert.SerializeObject(reply));
                }
            }
            return(response);
        }
        public void CreatePaymentTest_Validate_Approve_Status_Balance_Check()
        {
            decimal initialBalance       = InMemoryData.CurrentBalance;
            CreatePaymentRequest request = new CreatePaymentRequest {
                Amount = 10, PaymentDate = DateTime.Now
            };
            PaymentValidatorService validatorService = new PaymentValidatorService();
            PaymentService          paymentService   = new PaymentService(validatorService);
            CreatePaymentResponse   response         = paymentService.CreatePayment(request);

            if (response.IsValid && response.Payment != null &&
                response.Payment.RunningBalance == initialBalance &&
                response.ErrorMessages.Count == 0 &&
                response.Payment.Status == "Pending")
            {
                ApprovePaymentRequest approvePaymentRequest = new ApprovePaymentRequest();
                approvePaymentRequest.PaymentId = response.Payment.PaymentId;
                ApprovePaymentResponse approvePaymentResponse = paymentService.ApprovePayment(approvePaymentRequest);
                if (approvePaymentResponse.IsValid)
                {
                    Assert.IsTrue(approvePaymentResponse.Payment.Status == "Processed");
                    Assert.IsTrue(approvePaymentResponse.Payment.RunningBalance == (initialBalance - request.Amount));
                    Assert.IsTrue(approvePaymentResponse.Payment.Amount == request.Amount);
                }
            }
            else
            {
                string msg       = string.Empty;
                string delimiter = Environment.NewLine;
                response.ErrorMessages.ForEach(x => msg += x + delimiter);
                Assert.Fail(msg);
            }
        }
Exemple #7
0
        public async Task <CreatePaymentResponse> GetPaymentResponseAsync(string paymentId)
        {
            // Console.WriteLine($"GetPaymentRequestAsync called with {this._httpContextAccessor.HttpContext.Request.Headers[HEADER_VTEX_ACCOUNT]},master,{this._environmentVariableProvider.ApplicationName},{this._environmentVariableProvider.ApplicationVendor},{this._environmentVariableProvider.Region}");

            var request = new HttpRequestMessage
            {
                Method     = HttpMethod.Get,
                RequestUri = new Uri($"http://vbase.{this._environmentVariableProvider.Region}.vtex.io/{this._httpContextAccessor.HttpContext.Request.Headers[HEADER_VTEX_ACCOUNT]}/master/buckets/{this._applicationName}/{RESPONSE_BUCKET}/files/{paymentId}"),
            };

            string authToken = this._httpContextAccessor.HttpContext.Request.Headers[HEADER_VTEX_CREDENTIAL];

            if (authToken != null)
            {
                request.Headers.Add(AUTHORIZATION_HEADER_NAME, authToken);
            }

            var response = await _httpClient.SendAsync(request);

            string responseContent = await response.Content.ReadAsStringAsync();

            if (response.StatusCode == HttpStatusCode.NotFound)
            {
                return(null);
            }

            // A helper method is in order for this as it does not return the stack trace etc.
            response.EnsureSuccessStatusCode();

            CreatePaymentResponse paymentResponse = JsonConvert.DeserializeObject <CreatePaymentResponse>(responseContent);

            return(paymentResponse);
        }
Exemple #8
0
        public async Task PostCallbackResponse(string callbackUrl, CreatePaymentResponse createPaymentResponse)
        {
            HttpResponseMessage response = new HttpResponseMessage();

            // Internal vtex posts must be to http with use https header
            callbackUrl = callbackUrl.Replace("https", "http");

            try
            {
                var jsonSerializedPaymentResponse = JsonConvert.SerializeObject(createPaymentResponse);
                var request = new HttpRequestMessage
                {
                    Method     = HttpMethod.Post,
                    RequestUri = new Uri(callbackUrl),
                    Content    = new StringContent(jsonSerializedPaymentResponse, Encoding.UTF8, APPLICATION_JSON)
                };

                string authToken = this._httpContextAccessor.HttpContext.Request.Headers[HEADER_VTEX_CREDENTIAL];
                if (authToken != null)
                {
                    request.Headers.Add(AUTHORIZATION_HEADER_NAME, authToken);
                }

                response = await _httpClient.SendAsync(request);
            }
            catch (Exception ex)
            {
                _context.Vtex.Logger.Error("PostCallBackResponse", null, $"PostCallbackResponse {callbackUrl} Error: {ex.Message} InnerException: {ex.InnerException} StackTrace: {ex.StackTrace}", ex);
            }

            response.EnsureSuccessStatusCode();
        }
        public async Task Test()
        {
            CreatePaymentRequest body = new CreatePaymentRequest();

            Order order = new Order();

            AmountOfMoney amountOfMoney = new AmountOfMoney();

            amountOfMoney.CurrencyCode = ("EUR");
            amountOfMoney.Amount       = (100L);
            order.AmountOfMoney        = (amountOfMoney);

            Customer customer = new Customer();

            customer.Locale = ("en");

            Address billingAddress = new Address();

            billingAddress.CountryCode = ("NL");
            customer.BillingAddress    = (billingAddress);

            order.Customer = (customer);
            body.Order     = (order);

            RedirectionData redirectionData = new RedirectionData();

            redirectionData.ReturnUrl = ("http://example.com/");

            RedirectPaymentMethodSpecificInput paymentMethodSpecificInput = new RedirectPaymentMethodSpecificInput();

            paymentMethodSpecificInput.RedirectionData  = redirectionData;
            paymentMethodSpecificInput.PaymentProductId = (809);

            RedirectPaymentProduct809SpecificInput paymentProductSpecificInput = new RedirectPaymentProduct809SpecificInput();

            paymentProductSpecificInput.IssuerId = ("INGBNL2A");
            paymentMethodSpecificInput.PaymentProduct809SpecificInput = (paymentProductSpecificInput);

            body.RedirectPaymentMethodSpecificInput = (paymentMethodSpecificInput);

            string      idempotenceKey = Guid.NewGuid().ToString();
            CallContext context        = new CallContext().WithIdempotenceKey(idempotenceKey);

            using (Client client = GetClient())
            {
                CreatePaymentResponse response = await client.Merchant(GetMerchantId()).Payments().Create(body, context);

                string paymentId = response.Payment.Id;

                Assert.AreEqual(idempotenceKey, context.IdempotenceKey);
                Assert.Null(context.IdempotenceRequestTimestamp);

                response = await client.Merchant(GetMerchantId()).Payments().Create(body, context);

                Assert.AreEqual(paymentId, response.Payment.Id);

                Assert.AreEqual(idempotenceKey, context.IdempotenceKey);
                Assert.NotNull(context.IdempotenceRequestTimestamp);
            }
        }
 public static void SetPaymentResponse(this CreatePaymentResponse res, Payment payment)
 {
     res.PaymentId                 = payment.Id;
     res.PaymentCode               = payment.PaymentCode;
     res.CreateBy                  = payment.CreatedBy;
     res.CreateDate                = payment.CreatedDate;
     res.UpdateBy                  = payment.UpdatedBy;
     res.UpdateDate                = payment.UpdatedDate;
     res.CustomerIDMPartyID        = payment.CustomerIdmPartyId;
     res.CustomerCode              = null;
     res.CustomerName              = payment.CustomerName;
     res.CustomerAddress           = payment.CustomerAddress;
     res.CustomerAccountNumber     = payment.CustomerRefundAccountNo;
     res.CustomerAccountName       = payment.CustomerRefundAccountName;
     res.CustomerAccountBankId     = payment.CustomerRefundBankId;
     res.CustomerMobilePhoneNumber = payment.CustomerMobilePhoneNo;
     res.Remark                    = payment.Remark;
     res.Ref1                      = payment.Ref1;
     res.Ref2                      = payment.Ref2;
     res.Ref3                      = payment.Ref3;
     res.PaymentStatus             = payment.Status;
     res.RemainingAmount           = payment.RemainingAmount();
     res.GrandTotal                = payment.GrandTotal();
     res.TotalVatAmount            = payment.TotalVat();
     res.TotalWithholdingTaxAmount = payment.TotalWithholdingTax();
     res.TotalBeforeAdjustment     = payment.TotalNoDiscount();
     res.TotalAdjustment           = payment.TotalDiscount();
     res.PaymentItems              = payment.PaymentItems.CreatePaymentResponseItem();
 }
        public async Task <IActionResult> ProcessPaymentAsync(string nonce)
        {
            try
            {
                Square.Environment environment = appSettings.Environment == "sandbox" ?
                                                 Square.Environment.Sandbox : Square.Environment.Production;

                // Build base client
                SquareClient client = new SquareClient.Builder()
                                      .Environment(environment)
                                      .AccessToken(this.appSettings.AccessToken)
                                      .Build();

                IPaymentsApi         PaymentsApi  = client.PaymentsApi;
                CreatePaymentRequest request_body = new CreatePaymentRequest(nonce, this.NewIdempotencyKey(), new Money(100, "USD"));

                CreatePaymentResponse responce = await PaymentsApi.CreatePaymentAsync(request_body);

                if (responce?.Payment?.Status == "COMPLETED")
                {
                    //this.UpdateCart(new CartModel());
                    return(this.Ok());
                }
                else
                {
                    return(this.BadRequest($"STATUS: {responce?.Payment?.Status}"));
                }
            }
            catch (Exception ex)
            {
                return(this.BadRequest($"PaymentError: { ex.Message }"));
            }
        }
Exemple #12
0
        public async Task TestIdempotenceFirstRequest()
        {
            string body           = idempotenceSucessJson;
            string idempotenceKey = Guid.NewGuid().ToString();

            IDictionary <string, string> responseHeaders = new Dictionary <string, string>
            {
                { "Location", "http://localhost/v2/20000/payments/000002000020142549460000100001" }
            };

            IDictionary <string, string> requestHeaders = new Dictionary <string, string>();

            CallContext context = new CallContext().WithIdempotenceKey(idempotenceKey);

            using (MockServer host = new MockServer(Port, "/v2/20000/payments", (request, response, arg3) =>
            {
                RecordRequest((HttpStatusCode)201, request, requestHeaders, response, responseHeaders);
                return(body);
            }))
                using (IClient client = CreateClient())
                {
                    CreatePaymentRequest request = CreateRequest();

                    CreatePaymentResponse response = await client.WithNewMerchant("20000").Payments.CreatePayment(request, context)
                                                     .ConfigureAwait(false);

                    Assert.NotNull(response);
                    Assert.NotNull(response.Payment);
                    Assert.NotNull(response.Payment.Id);
                }
            Assert.AreEqual(idempotenceKey, requestHeaders[("X-GCS-Idempotence-Key")]);

            Assert.AreEqual(idempotenceKey, context.IdempotenceKey);
            Assert.Null(context.IdempotenceRequestTimestamp);
        }
        public void CreatePaymentTest_NotEnoughBalance()
        {
            decimal initialBalance         = InMemoryData.CurrentBalance;
            CreatePaymentResponse response = CreatePaymentResponse(100001m, DateTime.Now);

            AssertForCreatePaymentTests(response, initialBalance, "Not Enough Balance");
        }
Exemple #14
0
        public async Task TestIdempotenceSecondRequest()
        {
            string body           = idempotenceSucessJson;
            string idempotenceKey = Guid.NewGuid().ToString();
            double idempotenceRequestTimestamp           = (DateTime.UtcNow - Jan1st1970).TotalMilliseconds;
            IDictionary <string, string> responseHeaders = new Dictionary <string, string>(1);

            responseHeaders.Add("Location", "http://localhost/v1/20000/payments/000002000020142549460000100001");
            responseHeaders.Add("X-GCS-Idempotence-Request-Timestamp", idempotenceRequestTimestamp.ToString());
            IDictionary <string, string> requestHeaders = new Dictionary <string, string>();

            CallContext context = new CallContext().WithIdempotenceKey(idempotenceKey);

            using (MockServer host = new MockServer(Port, "/v1/20000/payments", (request, response, arg3) =>
            {
                RecordRequest((HttpStatusCode)201, request, requestHeaders, response, responseHeaders);
                return(body);
            }))
                using (Client client = CreateClient())
                {
                    CreatePaymentRequest request = CreateRequest();

                    CreatePaymentResponse response = await client.Merchant("20000").Payments().Create(request, context);

                    Assert.NotNull(response);
                    Assert.NotNull(response.Payment);
                    Assert.NotNull(response.Payment.Id);
                }
            Assert.AreEqual(idempotenceKey, requestHeaders[("X-GCS-Idempotence-Key")]);

            Assert.AreEqual(idempotenceKey, context.IdempotenceKey);
            Assert.Null(context.IdempotenceRequestTimestamp);
        }
Exemple #15
0
 private static void ValidateResponse(CreatePaymentResponse response)
 {
     if (response.Status != "Ok")
     {
         throw new ValidationException("Status of the BitBayPay API call has failed");
     }
 }
 private void AssertForCreatePaymentTests(CreatePaymentResponse response, decimal initialBalance, string errMsg)
 {
     Assert.IsFalse(response.IsValid);
     Assert.IsNull(response.Payment);
     Assert.IsTrue(response.ErrorMessages.Count > 0);
     Assert.IsTrue(InMemoryData.CurrentBalance == initialBalance);
     Assert.IsTrue(response.ErrorMessages[0] == errMsg);
 }
Exemple #17
0
        public async Task Test()
        {
            CreatePaymentRequest body = new CreatePaymentRequest
            {
                Order = new Order
                {
                    AmountOfMoney = new AmountOfMoney
                    {
                        CurrencyCode = "EUR",
                        Amount       = 100L
                    },
                    Customer = new Customer
                    {
                        Locale         = "en",
                        BillingAddress = new Address
                        {
                            CountryCode = "NL"
                        }
                    }
                },
                CardPaymentMethodSpecificInput = new CardPaymentMethodSpecificInput
                {
                    PaymentProductId   = 1,
                    IsRecurring        = false,
                    SkipAuthentication = true,
                    Card = new Card
                    {
                        CardholderName = "Wile E. Coyote",
                        CardNumber     = "4330264936344675",
                        ExpiryDate     = "1230",
                        Cvv            = "123"
                    }
                }
            };

            string      idempotenceKey = Guid.NewGuid().ToString();
            CallContext context        = new CallContext().WithIdempotenceKey(idempotenceKey);

            using (Client client = GetClient())
            {
                CreatePaymentResponse response = await client.WithNewMerchant(GetMerchantId()).Payments.CreatePayment(body, context)
                                                 .ConfigureAwait(false);

                string paymentId = response.Payment.Id;

                Assert.AreEqual(idempotenceKey, context.IdempotenceKey);
                Assert.Null(context.IdempotenceRequestTimestamp);

                response = await client.WithNewMerchant(GetMerchantId()).Payments.CreatePayment(body, context)
                           .ConfigureAwait(false);

                Assert.AreEqual(paymentId, response.Payment.Id);

                Assert.AreEqual(idempotenceKey, context.IdempotenceKey);
                Assert.NotNull(context.IdempotenceRequestTimestamp);
            }
        }
        private CreatePaymentResponse CreatePaymentResponse(decimal amount, DateTime paymentDate)
        {
            CreatePaymentRequest request = new CreatePaymentRequest {
                Amount = amount, PaymentDate = paymentDate
            };
            PaymentValidatorService validatorService = new PaymentValidatorService();
            PaymentService          paymentService   = new PaymentService(validatorService);
            CreatePaymentResponse   response         = paymentService.CreatePayment(request);

            return(response);
        }
Exemple #19
0
        /// <summary>
        /// https://{{providerApiEndpoint}}/payments
        /// Creates a new payment and/or initiates the payment flow.
        /// </summary>
        /// <param name="createPaymentRequest"></param>
        /// <returns></returns>
        public async Task <IActionResult> CreatePayment()
        {
            string publicKey  = HttpContext.Request.Headers[AffirmConstants.PublicKeyHeader];
            var    bodyAsText = await new System.IO.StreamReader(HttpContext.Request.Body).ReadToEndAsync();
            CreatePaymentRequest  createPaymentRequest = JsonConvert.DeserializeObject <CreatePaymentRequest>(bodyAsText);
            CreatePaymentResponse paymentResponse      = await this._affirmPaymentService.CreatePayment(createPaymentRequest, publicKey);

            Response.Headers.Add("Cache-Control", "private");

            return(Json(paymentResponse));
        }
Exemple #20
0
        public IActionResult Paid()
        {
            Square.Environment environment = this.appSettings.Environment == "sandbox" ?
                                             Square.Environment.Sandbox : Square.Environment.Production;

            // Build base client
            SquareClient client = new SquareClient.Builder()
                                  .Environment(environment)
                                  .AccessToken(this.appSettings.AccessToken)
                                  .Build();


            string       nonce       = Request.Form["nonce"];
            IPaymentsApi PaymentsApi = client.PaymentsApi;
            // Every payment you process with the SDK must have a unique idempotency key.
            // If you're unsure whether a particular payment succeeded, you can reattempt
            // it with the same idempotency key without worrying about double charging
            // the buyer.
            string uuid = this.NewIdempotencyKey();

            // Monetary amounts are specified in the smallest unit of the applicable currency.
            // This amount is in cents. It's also hard-coded for $1.00,
            // which isn't very useful.
            Money amount = new Money.Builder()
                           .Amount(500L)
                           .Currency("USD")
                           .Build();

            // To learn more about splitting payments with additional recipients,
            // see the Payments API documentation on our [developer site]
            // (https://developer.squareup.com/docs/payments-api/overview).
            CreatePaymentRequest createPaymentRequest = new CreatePaymentRequest.Builder(nonce, uuid, amount)
                                                        .Note("From Square Visit Cart App")
                                                        .Build();

            try
            {
                CreatePaymentResponse response = PaymentsApi.CreatePayment(createPaymentRequest);
                PaymentResultModel    model    = new PaymentResultModel
                {
                    ResultMessage = "Payment complete! " + response.Payment.Note
                };

                return(View(model));
            }
            catch (ApiException ex)
            {
                return(View("PaymentError", new ErrorViewModel {
                    Message = ex.Message
                }));
            }
        }
Exemple #21
0
        public async Task <CreatePaymentResponse> CreatePayment(CreatePaymentRequest request, Merchant merchant)
        {
            try
            {
                if (merchant == null)
                {
                    return(null);
                }

                _log.LogInformation($"Requesting bank for merchant {merchant.Id} : {request.Amount:C2}");

                var bankResponse = await _bankGateway.SubmitPayment(PaymentMapper.MapGatewayRequest(request));

                _log.LogInformation($"Bank response for merchant {merchant.Id} : {bankResponse.Status} ");



                var payment = await _paymentRepository.Add(PaymentMapper.MapPayment(bankResponse, merchant, _encryptionProvier));

                var isPaymentSuccessfull = bankResponse.Status == BankGatewayPaymentStatus.Successfull;
                var result = new CreatePaymentResponse {
                    IsSuccessfull = isPaymentSuccessfull
                };

                if (isPaymentSuccessfull)
                {
                    result.PaymentId = payment.Id;
                }
                else
                {
                    result.ErrorMessage = "Unable to process payment with Bank";
                }


                _log.LogInformation($"Created  Payment for  merchant {merchant.Id} : {result.PaymentId} ");

                return(result);
            }
            catch (Exception ex)
            {
                _log.LogError("Unabl to process paument", ex);

                return(new CreatePaymentResponse
                {
                    IsSuccessfull = false,
                    ErrorMessage = "An unexpected error occured, please try again later or contact support"
                });
            }
        }
        public async Task SendPaymentResponse(PaymentEntity paymentEntity, string corrId)
        {
            var msg = new CreatePaymentResponse
            {
                CorrelationId      = corrId,
                OrderId            = paymentEntity.OrderId,
                PaymentInformation = new PaymentInformation
                {
                    PaymentAmount = paymentEntity.AmountPayable,
                    PaymentId     = paymentEntity.PaymentId,
                    PaymentStatus = paymentEntity.PaymentStatus.GetDisplayName()
                }
            };

            await SendMessage(msg, corrId);
        }
Exemple #23
0
        public static DenhacResponse CreatePaymentService(string member_id, double amount, string payment_type_id, string notes)
        {
            var resultStr = CallGet(hostName + "/createpayment?member_id=" + member_id + "&amount=" + amount + "&payment_type_id=" + payment_type_id + "&notes=" + notes);
            CreatePaymentResponse responseObj = JsonConvert.DeserializeObject <CreatePaymentResponse>(resultStr);

            if (responseObj.created != null && responseObj.created.Equals("True"))
            {
                responseObj.transactionStatus = true;
            }
            else
            {
                responseObj.transactionStatus = false;
            }

            return(responseObj);
        }
Exemple #24
0
        public CreatePaymentResponse CreatePayment(CreatePaymentRequest req)
        {
            var res = new CreatePaymentResponse();

            try
            {
                using (var idmClient = new IDMServiceClient())
                    using (var container = new TransactionModelContainer())
                    {
                        ValidateCreatePaymentRequest(idmClient, req);
                        var payment = new Payment(
                            req.CreateBy,
                            req.CustomerIDMPartyID,
                            req.CustomerName,
                            req.CustomerAddress,
                            req.PaymentItems.CreatePaymentItems()
                            );

                        var grandTotal = payment.GrandTotal();
                        var credits    = container.CustomerCredits.Where(x =>
                                                                         x.CustomerIdmPartyId == req.CustomerIDMPartyID &&
                                                                         x.IsUsedOrRefund == false).ToList();

                        var credit = credits.GetCustomerCredit(grandTotal);

                        foreach (var c in credit)
                        {
                            payment.AddPaymentItem(PaymentItem.CreateCustomerCredit(c.Id, c.Amount));
                        }

                        CustomerCredit.UpdateCustomerCredit(credit);

                        container.Payments.AddObject(payment);
                        container.SaveChanges();

                        res.SetPaymentResponse(payment);
                        res.Succeed();
                    }
            }
            catch (Exception x)
            {
                res.Fail(x);
                CreateLog(req, x);
            }

            return(res);
        }
        public async Task <IActionResult> CreatePaymentRequest([FromBody] CreatePaymentRequestModel request)
        {
            if (string.IsNullOrWhiteSpace(request.SettlementAsset))
            {
                return(BadRequest(PaymentErrorResponseModel.Create(PaymentErrorType.InvalidSettlementAsset)));
            }

            if (string.IsNullOrWhiteSpace(request.PaymentAsset))
            {
                return(BadRequest(PaymentErrorResponseModel.Create(PaymentErrorType.InvalidPaymentAsset)));
            }

            try
            {
                var domainRequest =
                    Mapper.Map <CreatePaymentRequest>(request,
                                                      opt => opt.Items["MerchantId"] = _headersHelper.MerchantId);

                CreatePaymentResponse createResponse =
                    await _paymentRequestService.CreatePaymentRequestAsync(domainRequest);

                PaymentRequestDetailsModel paymentRequestDetails =
                    await _paymentRequestService.GetPaymentRequestDetailsAsync(_headersHelper.MerchantId,
                                                                               createResponse.Id);

                return(Ok(paymentRequestDetails.ToStatusApiModel()));
            }
            catch (InvalidSettlementAssetException ex)
            {
                _log.Error(ex, null, $"request: {request.ToJson()}");

                return(BadRequest(PaymentErrorResponseModel.Create(PaymentErrorType.InvalidSettlementAsset)));
            }
            catch (InvalidPaymentAssetException ex)
            {
                _log.Error(ex, null, $"request: {request.ToJson()}");

                return(BadRequest(PaymentErrorResponseModel.Create(PaymentErrorType.InvalidPaymentAsset)));
            }
            catch (Exception ex)
            {
                _log.Error(ex, null, $"request: {request.ToJson()}");

                throw;
            }
        }
        public async Task TestCreateSuccess()
        {
            var connectionMock = new Mock <IConnection>();

            connectionMock.Setup(arg => arg.Post(Moq.It.IsAny <Uri>(), Moq.It.IsAny <IEnumerable <IRequestHeader> >(), Moq.It.IsAny <string>())).ReturnsAsync(new Response((HttpStatusCode)201, pendingApprovalJson, null));

            Uri apiEndpoint = new Uri("http://localhost");
            var session     = new Session(apiEndpoint, connectionMock.Object, new DefaultAuthenticator(AuthorizationType.V1HMAC, "test", "test"), new MetaDataProvider("Ingenico"));

            Client client = Factory.CreateClient(session);

            CreatePaymentRequest body = CreateRequest();

            CreatePaymentResponse response = await client.Merchant("merchantId").Payments().Create(body);

            Assert.AreEqual("000002000020142549460000100001", response.Payment.Id);
            Assert.AreEqual("PENDING_APPROVAL", response.Payment.Status);
        }
        public async Task <string> PostCallbackResponse(string callbackUrl, CreatePaymentResponse createPaymentResponse)
        {
            string message = string.Empty;  // Empty message signifies success
            HttpResponseMessage response = new HttpResponseMessage();

            try
            {
                // Internal vtex posts must be to http with use https header
                callbackUrl = callbackUrl.Replace("https", "http");

                var jsonSerializedPaymentResponse = JsonConvert.SerializeObject(createPaymentResponse);
                var request = new HttpRequestMessage
                {
                    Method     = HttpMethod.Post,
                    RequestUri = new Uri(callbackUrl),
                    Content    = new StringContent(jsonSerializedPaymentResponse, Encoding.UTF8, APPLICATION_JSON)
                };

                request.Headers.Add(FlowFinanceConstants.USE_HTTPS_HEADER_NAME, "true");
                string authToken = this._httpContextAccessor.HttpContext.Request.Headers[HEADER_VTEX_CREDENTIAL];
                if (authToken != null)
                {
                    request.Headers.Add(AUTHORIZATION_HEADER_NAME, authToken);
                    request.Headers.Add(VTEX_ID_HEADER_NAME, authToken);
                }

                var client = _clientFactory.CreateClient();
                response = await client.SendAsync(request);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"PostCallbackResponse to '{callbackUrl}' Error: {ex.Message} InnerException: {ex.InnerException} StackTrace: {ex.StackTrace}");
                message = $"PostCallbackResponse '{createPaymentResponse.status}' to '{callbackUrl}' Error: {ex.Message} InnerException: {ex.InnerException} StackTrace: {ex.StackTrace}";
            }

            //response.EnsureSuccessStatusCode();
            if (!response.IsSuccessStatusCode)
            {
                Console.WriteLine($"PostCallbackResponse to '{callbackUrl}' status [{response.StatusCode}]");
                message = $"PostCallbackResponse '{createPaymentResponse.status}' to '{callbackUrl}' status [{response.StatusCode}]";
            }

            return(message);
        }
        /// <summary>
        /// Executes the WorkFlow.
        /// </summary>
        /// <param name="crmWorkflowContext">The <see cref="WorkFlowActivityBase.LocalWorkflowContext"/> which contains the
        /// <param name="executionContext" > <see cref="CodeActivityContext"/>
        /// </param>
        /// <remarks>
        /// For improved performance, Microsoft Dynamics 365 caches WorkFlow instances.
        /// The WorkFlow's Execute method should be written to be stateless as the constructor
        /// is not called for every invocation of the WorkFlow. Also, multiple system threads
        /// could execute the WorkFlow at the same time. All per invocation state information
        /// is stored in the context. This means that you should not use global variables in WorkFlows.
        /// </remarks>
        public override void ExecuteCRMWorkFlowActivity(CodeActivityContext executionContext, LocalWorkflowContext crmWorkflowContext)
        {
            var tracingService = executionContext.GetExtension <ITracingService>();

            tracingService.Trace("CreatePayment starting...");

            try
            {
                // 1. Validation
                ValidateNotNull(crmWorkflowContext);

                // 2. Prepare API Request
                tracingService.Trace("Calling PrepareCardPaymentRequest...");
                CreatePaymentRequest apiRequest = this.PrepareCardPaymentRequest(executionContext);

                // 2. Retrieve Configuration
                tracingService.Trace("Calling RetrieveCardPaymentServiceConfiguration...");
                RestServiceConfiguration cardServiceConfiguration = this.RetrieveCardPaymentServiceConfiguration(executionContext, ConfigurationPrefix.Get(executionContext));

                // 3. Set-up the Api Service
                tracingService.Trace("Instantiating CardPaymentService...");
                CardPaymentService cardPaymentService = new CardPaymentService(cardServiceConfiguration);

                // 4. Call the API
                tracingService.Trace("Calling GovPay CreatePayment with amount='{0}', description='{1}', reference='{2}', returnUrl='{3}'", apiRequest.amount, apiRequest.description, apiRequest.reference, apiRequest.return_url);
                CreatePaymentResponse apiResponse = cardPaymentService.CreatePayment(apiRequest);

                // TODO Log request and Response

                // 5. Return the response
                if (apiResponse != null && apiResponse.error_message != null)
                {
                    tracingService.Trace("Error message: {0}", apiResponse.error_message);
                }
                tracingService.Trace("Calling PrepareOutputParameters...");
                this.PrepareOutputParameters(executionContext, apiResponse, tracingService);
            }
            catch (Exception ex)
            {
                // Todo: Log the Error
                tracingService.Trace("Exception: " + ex);
                throw ex;
            }
        }
Exemple #29
0
        public CreatePaymentResponse CreatePayment(string baseUri, double amount)
        {
            string guid = Convert.ToString((new Random()).Next(100000));
            var createdPayment = CreatePaymentInternal(_apiContext, baseUri + "guid=" + guid, amount);
            List<Links> links = createdPayment.links;
            string paypalRedirectUrl = null;
            var redirectLink = links.FirstOrDefault(x => x.rel.ToLower().Trim().Equals("approval_url"));
            if (redirectLink==null)
                throw new Exception("Redirect link is null");
            paypalRedirectUrl = redirectLink.href;
            var response = new CreatePaymentResponse
            {
                Guid = guid,
                PaymentId = createdPayment.id,
                RedirectUrl = paypalRedirectUrl
            };

            return response;
        }
        public void CreatePaymentTest_Validate_status()
        {
            CreatePaymentResponse response = CreatePaymentResponse(10m, DateTime.Now);

            if (response != null && response.IsValid && response.Payment != null &&
                response.Payment.RunningBalance == InMemoryData.CurrentBalance &&
                response.ErrorMessages.Count == 0 &&
                response.Payment.Status == "Pending")
            {
                Assert.IsTrue(response.IsValid);
            }
            else
            {
                string msg       = string.Empty;
                string delimiter = Environment.NewLine;
                response?.ErrorMessages.ForEach(x => msg += x + delimiter);
                Assert.Fail(msg);
            }
        }
Exemple #31
0
        /// <summary>
        /// Read the charge information, current charge status, and checkout data
        /// </summary>
        /// <param name="paymentIdentifier">Payment GUID</param>
        /// <param name="token"></param>
        /// <returns></returns>
        public async Task <IActionResult> ReadCharge(string paymentIdentifier, string sandboxMode)
        {
            string privateKey = HttpContext.Request.Headers[AffirmConstants.PrivateKeyHeader];
            string publicKey  = HttpContext.Request.Headers[AffirmConstants.PublicKeyHeader];

            if (string.IsNullOrWhiteSpace(privateKey) || string.IsNullOrWhiteSpace(publicKey))
            {
                return(BadRequest());
            }
            else
            {
                CreatePaymentResponse paymentResponse = await this._affirmPaymentService.ReadCharge(paymentIdentifier, publicKey, privateKey, bool.Parse(sandboxMode));

                _context.Vtex.Logger.Info("ReadCharge", null, $"{paymentIdentifier} {JsonConvert.SerializeObject(paymentResponse)}");
                Response.Headers.Add("Cache-Control", "private");

                return(Json(paymentResponse));
            }
        }