Exemple #1
0
        static async Task <string> CancelPayment(Guid paymentId)
        {
            Console.WriteLine();
            Console.WriteLine("******Cacel payment test***********");
            Console.WriteLine();
            Uri u = new Uri(baseUrl + "cancelpayment");

            var response = string.Empty;

            using (var client = new HttpClient())
            {
                CancelPaymentRequest payload = new CancelPaymentRequest();
                payload.PaymentId = paymentId;
                HttpResponseMessage res = await client.PostAsJsonAsync(u, payload);

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

                    if (reply.Payment.PaymentId == paymentId && reply.Payment.Status == "Closed")
                    {
                        Console.WriteLine("Cancel payment failed for  payment id " + paymentId);
                    }
                    return(JsonConvert.SerializeObject(reply));
                }
            }
            return(response);
        }
        public async void Example()
        {
#pragma warning disable 0168
            using (Client client = GetClient())
            {
                CancelPaymentResponse response = await client.Merchant("merchantId").Payments().Cancel("paymentId");
            }
#pragma warning restore 0168
        }
        /// <summary>
        /// Cancels a payment that was not yet approved or captured (settled).
        /// </summary>
        /// <param name="cancelPaymentRequest"></param>
        /// <returns></returns>
        public async Task <CancelPaymentResponse> CancelPayment(CancelPaymentRequest cancelPaymentRequest, string publicKey, string privateKey)
        {
            CancelPaymentResponse cancelPaymentResponse = new CancelPaymentResponse
            {
                cancellationId = null,
                code           = null,
                message        = "Empty",
                paymentId      = cancelPaymentRequest.paymentId,
                requestId      = cancelPaymentRequest.requestId
            };

            // Load request from storage for order id
            CreatePaymentRequest paymentRequest = await this._paymentRequestRepository.GetPaymentRequestAsync(cancelPaymentRequest.paymentId);

            if (paymentRequest == null)
            {
                cancelPaymentResponse.message = $"Could not load Payment Request for Payment Id {cancelPaymentRequest.paymentId}.";
                _context.Vtex.Logger.Warn("CancelPayment", null, $"Could not load Payment Request for Payment Id: {cancelPaymentRequest.paymentId}");
            }
            else
            {
                // Get Affirm id from storage
                cancelPaymentRequest.authorizationId = paymentRequest.transactionId;
            }

            if (!string.IsNullOrEmpty(cancelPaymentRequest.authorizationId))
            {
                bool       isLive         = !cancelPaymentRequest.sandboxMode; // await this.GetIsLiveSetting();
                IAffirmAPI affirmAPI      = new AffirmAPI(_httpContextAccessor, _httpClient, isLive, _context);
                dynamic    affirmResponse = await affirmAPI.VoidAsync(publicKey, privateKey, cancelPaymentRequest.authorizationId);

                // If affirmResponse.reference_id is null, assume the payment was never authorized.
                // TODO: Make a call to 'Read' to get token status.
                // This will require storing and loading the token from vbase.
                cancelPaymentResponse = new CancelPaymentResponse
                {
                    paymentId      = cancelPaymentRequest.paymentId,
                    cancellationId = affirmResponse.id ?? null,
                    code           = affirmResponse.type ?? affirmResponse.Error.Code,
                    message        = affirmResponse.created ?? affirmResponse.Error.Message,
                    requestId      = cancelPaymentRequest.requestId
                };
            }
            else
            {
                // Assume that the order was never authorized
                cancelPaymentResponse.cancellationId = "not_authorized";
            }

            return(cancelPaymentResponse);
        }
Exemple #4
0
        public IPaymentResponse ExecuteAction(IRequest req)
        {
            CancelPaymentResponse response = ValidatorService.ValidateCancelPayment((CancelPaymentRequest)req);

            if (response.IsValid)
            {
                response.Payment.Status = "Closed";
                //	InMemoryData.CurrentBalance -= response.Payment.Amount;
                response.Payment.RunningBalance      = InMemoryData.CurrentBalance;
                response.Payment.CancellationMessage = ((CancelPaymentRequest)req).CancelReason;
                return(response);
            }
            return(response);
        }
        public CancelPaymentResponse ValidateCancelPayment(CancelPaymentRequest cancelPaymentRequest)
        {
            CancelPaymentResponse response = new CancelPaymentResponse();
            Payment payment = InMemoryData.Payments.FirstOrDefault(x => x.PaymentId == cancelPaymentRequest.PaymentId);

            if (payment == null)
            {
                response.ErrorMessages.Add("No such payment exists!!!??");
            }
            else if (payment.Status != "Pending")
            {
                response.ErrorMessages.Add("Only pending payment can be cancelled");
            }
            else
            {
                response.IsValid = true;
                response.Payment = payment;
            }
            return(response);
        }
Exemple #6
0
        /// <summary>
        /// https://{{providerApiEndpoint}}/payments/{{paymentId}}/cancellations
        /// </summary>
        /// <param name="paymentId">VTEX payment ID from this payment</param>
        /// <param name="cancelPaymentRequest"></param>
        /// <returns></returns>
        public async Task <IActionResult> CancelPayment(string paymentId)
        {
            string privateKey = HttpContext.Request.Headers[AffirmConstants.PrivateKeyHeader];
            string publicKey  = HttpContext.Request.Headers[AffirmConstants.PublicKeyHeader];

            var bodyAsText = await new System.IO.StreamReader(HttpContext.Request.Body).ReadToEndAsync();
            CancelPaymentRequest cancelPaymentRequest = JsonConvert.DeserializeObject <CancelPaymentRequest>(bodyAsText);

            if (string.IsNullOrWhiteSpace(privateKey) || string.IsNullOrWhiteSpace(publicKey))
            {
                return(BadRequest());
            }
            else
            {
                CancelPaymentResponse cancelResponse = await this._affirmPaymentService.CancelPayment(cancelPaymentRequest, publicKey, privateKey);

                _context.Vtex.Logger.Info("CancelPayment", null, $"{bodyAsText} {JsonConvert.SerializeObject(cancelResponse)}");

                return(Json(cancelResponse));
            }
        }
        public void CreatePaymentTest_Disallow_Cancel_On_Closed_Payments()
        {
            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")
            {
                CancelPaymentRequest cancelPaymentRequest = new CancelPaymentRequest
                {
                    PaymentId = response.Payment.PaymentId
                };
                CancelPaymentResponse cancelPaymentResponse = paymentService.CancelPayment(cancelPaymentRequest);
                if (cancelPaymentResponse.IsValid)
                {
                    CancelPaymentRequest tryCancelClosedPayment = new CancelPaymentRequest();
                    tryCancelClosedPayment.PaymentId = cancelPaymentResponse.Payment.PaymentId;
                    CancelPaymentResponse disAllowedAction = paymentService.CancelPayment(tryCancelClosedPayment);
                    Assert.IsFalse(disAllowedAction.IsValid);
                    Assert.IsTrue(disAllowedAction.ErrorMessages.Count == 1);
                    Assert.IsTrue(disAllowedAction.ErrorMessages[0] == "Only pending payment can be cancelled");
                }
            }
            else
            {
                string msg       = string.Empty;
                string delimiter = Environment.NewLine;
                response.ErrorMessages.ForEach(x => msg += x + delimiter);
                Assert.Fail(msg);
            }
        }
        public void CreatePaymentTest_Validate_Cancel_Status_Balance_And_Cancel_Reason_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")
            {
                CancelPaymentRequest cancelPaymentRequest = new CancelPaymentRequest
                {
                    PaymentId    = response.Payment.PaymentId,
                    CancelReason = "I am testing if can cancel works or not"
                };
                CancelPaymentResponse cancelPaymentResponse = paymentService.CancelPayment(cancelPaymentRequest);
                if (cancelPaymentResponse.IsValid)
                {
                    Assert.IsTrue(cancelPaymentResponse.Payment.Status == "Closed");
                    Assert.IsTrue(cancelPaymentResponse.Payment.CancellationMessage == cancelPaymentRequest.CancelReason);

                    Assert.IsTrue(cancelPaymentResponse.Payment.RunningBalance == initialBalance);
                    Assert.IsTrue(cancelPaymentResponse.Payment.Amount == request.Amount);
                }
            }
            else
            {
                string msg       = string.Empty;
                string delimiter = Environment.NewLine;
                response.ErrorMessages.ForEach(x => msg += x + delimiter);
                Assert.Fail(msg);
            }
        }