/// <summary> /// Refunds a payment /// </summary> /// <param name="refundPaymentRequest">Request</param> /// <returns>Result</returns> public RefundPaymentResult Refund(RefundPaymentRequest refundPaymentRequest) { var result = new RefundPaymentResult(); PrepareAuthorizeNet(); var maskedCreditCardNumberDecrypted = _encryptionService.DecryptText(refundPaymentRequest.Order.MaskedCreditCardNumber); if (String.IsNullOrEmpty(maskedCreditCardNumberDecrypted) || maskedCreditCardNumberDecrypted.Length < 4) { result.AddError("Last four digits of Credit Card Not Available"); return(result); } var lastFourDigitsCardNumber = maskedCreditCardNumberDecrypted.Substring(maskedCreditCardNumberDecrypted.Length - 4); var creditCard = new creditCardType { cardNumber = lastFourDigitsCardNumber, expirationDate = "XXXX" }; var codes = (string.IsNullOrEmpty(refundPaymentRequest.Order.CaptureTransactionId) ? refundPaymentRequest.Order.AuthorizationTransactionCode : refundPaymentRequest.Order.CaptureTransactionId).Split(','); var transactionRequest = new transactionRequestType { transactionType = transactionTypeEnum.refundTransaction.ToString(), amount = Math.Round(refundPaymentRequest.AmountToRefund, 2), refTransId = codes[0], currencyCode = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode, order = new orderType { //x_invoice_num is 20 chars maximum. hece we also pass x_description invoiceNumber = refundPaymentRequest.Order.OrderGuid.ToString().Substring(0, 20), description = string.Format("Full order #{0}", refundPaymentRequest.Order.OrderGuid) }, payment = new paymentType { Item = creditCard } }; var request = new createTransactionRequest { transactionRequest = transactionRequest }; // instantiate the contoller that will call the service var controller = new createTransactionController(request); controller.Execute(); GetApiResponse(controller, result.Errors); result.NewPaymentStatus = PaymentStatus.PartiallyRefunded; return(result); }
public static PtsV2PaymentsRefundPost201Response Run() { var id = ElectronicCheckDebits.Run().Id; string clientReferenceInformationCode = "TC50171_3"; Ptsv2paymentsClientReferenceInformation clientReferenceInformation = new Ptsv2paymentsClientReferenceInformation( Code: clientReferenceInformationCode ); Ptsv2paymentsidrefundsProcessingInformation processingInformation = new Ptsv2paymentsidrefundsProcessingInformation( ); string paymentInformationPaymentTypeName = "CHECK"; Ptsv2paymentsPaymentInformationPaymentType paymentInformationPaymentType = new Ptsv2paymentsPaymentInformationPaymentType( Name: paymentInformationPaymentTypeName ); Ptsv2paymentsidrefundsPaymentInformation paymentInformation = new Ptsv2paymentsidrefundsPaymentInformation( PaymentType: paymentInformationPaymentType ); string orderInformationAmountDetailsTotalAmount = "100"; string orderInformationAmountDetailsCurrency = "USD"; Ptsv2paymentsidcapturesOrderInformationAmountDetails orderInformationAmountDetails = new Ptsv2paymentsidcapturesOrderInformationAmountDetails( TotalAmount: orderInformationAmountDetailsTotalAmount, Currency: orderInformationAmountDetailsCurrency ); Ptsv2paymentsidrefundsOrderInformation orderInformation = new Ptsv2paymentsidrefundsOrderInformation( AmountDetails: orderInformationAmountDetails ); var requestObj = new RefundPaymentRequest( ClientReferenceInformation: clientReferenceInformation, ProcessingInformation: processingInformation, PaymentInformation: paymentInformation, OrderInformation: orderInformation ); try { var configDictionary = new Configuration().GetConfiguration(); var clientConfig = new CyberSource.Client.Configuration(merchConfigDictObj: configDictionary); var apiInstance = new RefundApi(clientConfig); PtsV2PaymentsRefundPost201Response result = apiInstance.RefundPayment(requestObj, id); Console.WriteLine(result); return(result); } catch (Exception e) { Console.WriteLine("Exception on calling the API : " + e.Message); return(null); } }
public async Task <RefundPaymentResult> RefundRequest(RefundPaymentRequest request) { string merchantId = request.BankParameters["merchantId"]; string terminalId = request.BankParameters["terminalId"]; //yapıkredi bankasında tutar bilgisinde nokta, virgül gibi değerler istenmiyor. 1.10 TL'lik işlem 110 olarak gönderilmeli. Yani tutarı 100 ile çarpabiliriz. string amount = (request.TotalAmount * 100m).ToString("N");//virgülden sonraki sıfırlara gerek yok string currencyCode = PaymentProviderFactory.CurrencyCodes[request.CurrencyIsoCode]; if (currencyCode == "TRY") { currencyCode = "TL";//yapıkredi halen eski Türk lirası kodunu kullanıyor } string requestXml = $@"<?xml version=""1.0"" encoding=""utf-8""?> <posnetRequest> <mid>{merchantId}</mid> <tid>{terminalId}</tid> <tranDateRequired>1</tranDateRequired> <return> <amount>{amount}</amount> <currencyCode>{currencyCode}</currencyCode> <hostLogKey>{request.ReferenceNumber.Split('-').First().Trim()}</hostLogKey> </return> </posnetRequest>"; var httpParameters = new Dictionary <string, string>(); httpParameters.Add("xmldata", requestXml); var response = await client.PostAsync(request.BankParameters["verifyUrl"], new FormUrlEncodedContent(httpParameters)); string responseContent = await response.Content.ReadAsStringAsync(); var xmlDocument = new XmlDocument(); xmlDocument.LoadXml(responseContent); if (xmlDocument.SelectSingleNode("posnetResponse/approved") == null || xmlDocument.SelectSingleNode("posnetResponse/approved").InnerText != "1") { string errorMessage = xmlDocument.SelectSingleNode("posnetResponse/respText")?.InnerText ?? string.Empty; if (string.IsNullOrEmpty(errorMessage)) { errorMessage = "Bankadan hata mesajı alınamadı."; } return(RefundPaymentResult.Failed(errorMessage)); } var transactionId = xmlDocument.SelectSingleNode("posnetResponse/hostlogkey")?.InnerText; return(RefundPaymentResult.Successed(transactionId)); }
public void When_order_id_is_not_specified_It_should_render_relative_url_with_transaction_id_and_amount() { var request = new RefundPaymentRequest(TransactionId, TotalAmount); var httpRequest = SUT.Create(request); httpRequest.ShouldBe().PostAgainst( "/transactions/{0}/refund/{1}", TransactionId, _totalAmountString); }
public int RefundPayment(RefundPaymentRequest request) { if (websocket != null) { RefundPaymentRequestMessage message = new RefundPaymentRequestMessage(); message.payload = request; websocket.Send(JsonUtils.serialize(message)); return(0); } return(-1); }
public static void StartDirectRefund(ICloverConnector cloverConnector, string paymentId, string orderId) { //cloverConnector.ResetDevice(); RefundPaymentRequest refundRequest = new RefundPaymentRequest(); refundRequest.PaymentId = paymentId; refundRequest.OrderId = orderId; refundRequest.FullRefund = true; cloverConnector.RefundPayment(refundRequest); }
/// <summary> /// Refunds a payment /// </summary> /// <param name="refundPaymentRequest">Request</param> /// <returns>Result</returns> public RefundPaymentResult Refund(RefundPaymentRequest refundPaymentRequest) { //create common query parameters for the request var refundParameters = CreateOxipayRefundRequest(refundPaymentRequest); var hmacSignature = GenerateHMAC(refundParameters); refundParameters.Add("signature", hmacSignature); var jsonRefundContent = JsonConvert.SerializeObject(refundParameters, new JsonSerializerSettings() { Formatting = Formatting.Indented }); //create post data var postData = Encoding.Default.GetBytes(jsonRefundContent); //create web request var serviceUrl = GetOxipayRefundUrl(); var request = (HttpWebRequest)WebRequest.Create(serviceUrl); request.Method = WebRequestMethods.Http.Post; request.Accept = "*/*"; request.ContentType = "application/json"; request.ContentLength = postData.Length; //request.UserAgent = SquarePaymentDefaults.UserAgent; //post request using (var stream = request.GetRequestStream()) { stream.Write(postData, 0, postData.Length); } //get response var httpResponse = (HttpWebResponse)request.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { if (httpResponse.StatusCode == HttpStatusCode.NoContent) { //successfully refunded return(new RefundPaymentResult { NewPaymentStatus = refundPaymentRequest.IsPartialRefund ? PaymentStatus.PartiallyRefunded : PaymentStatus.Refunded }); } else { return(new RefundPaymentResult { Errors = new[] { "Refund error" } }); } } }
public void Refund_first_line() { var refundLine1Request = new RefundPaymentRequest( TestState.FinalizeAuthorizationResponse.TransactionId, TestState.CreateOrderResponse.OrderId, TestState.CreateOrderRequest.LineItems[0].TotalLineAmount) .AddLineItem(TestState.CreateOrderRequest.LineItems[0]); var refundLine1Response = Client.RefundPayment(refundLine1Request); refundLine1Response.ShouldBe().PartiallyRefunded(refundLine1Request.TotalAmount); }
public RefundPaymentResult Refund(RefundPaymentRequest refundPaymentRequest) { var result = new RefundPaymentResult(); var cardknoxFacade = PrepareCardknoxFacade(); var cardknoxRequest = new CardknoxSDK.Actions.Refund.Request() { RefNum = refundPaymentRequest.Order.CaptureTransactionId, Amount = refundPaymentRequest.AmountToRefund }; var response = cardknoxFacade.Refund(cardknoxRequest) .GetAwaiter().GetResult(); //validate if (response == null) { return(result); } switch (response.ResponseType) { case CardknoxSDK.Infra.ResponseTypes.Accepted: if (refundPaymentRequest.IsPartialRefund) { result.NewPaymentStatus = PaymentStatus.PartiallyRefunded; } else { result.NewPaymentStatus = PaymentStatus.Refunded; } break; case CardknoxSDK.Infra.ResponseTypes.Declined: result.AddError($"Payment refund declined. Error code: {response.ErrorCode} - Error Message: {response.ErrorMessage}"); break; case CardknoxSDK.Infra.ResponseTypes.Error: result.AddError($"Payment refund error. Error code: {response.ErrorCode} - Error Message: {response.ErrorMessage}"); break; case CardknoxSDK.Infra.ResponseTypes.Timeout: result.AddError($"Payment refund timeout. Please try again. Error code: {response.ErrorCode} - Error Message: {response.ErrorMessage}"); break; case CardknoxSDK.Infra.ResponseTypes.HttpException: result.AddError($"Communication error. Please try again. Error code: {response.ErrorCode} - Error Message: {response.ErrorMessage}"); break; } return(result); }
private Dictionary <string, Object> VoidRequest(RefundPaymentRequest refundPaymentRequest) { Dictionary <string, string> refundParams = new Dictionary <string, string>(); Dictionary <string, Object> responseRefund = new Dictionary <string, Object>(); refundParams = GenerateVoidRequestParams(refundPaymentRequest.Order.Id); _logger.Information("TodoPago ParamsRefund : " + todoPagoBusinessService.serealizar(refundParams)); responseRefund = this.connector.VoidRequest(refundParams); _logger.Information("TodoPago resultRefund : " + todoPagoBusinessService.serealizarRefund(responseRefund)); return(responseRefund); }
public async Task <RefundPaymentResponse> RefundPayment(RefundPaymentRequest request) { request.SignRequest(this._signatureService); var refund = await this.AuthenticatedSendAsync <RefundPaymentRequest, RefundPaymentResponse>(request, request.Request(this._apiKey.Host)); if (refund.Signature == refund.CalculateSignature(this._signatureService)) { return(refund); } throw new Exception($"Signature error, response signature: {refund.Signature}, calculated signature: {refund.CalculateSignature(this._signatureService)}"); }
public async Task <RefundPaymentResult> RefundRequest(RefundPaymentRequest request) { string clientId = request.BankParameters["clientId"]; string userName = request.BankParameters["refundUsername"]; string password = request.BankParameters["refundUserPassword"]; string requestXml = $@"<?xml version=""1.0"" encoding=""utf-8""?> <CC5Request> <Name>{userName}</Name> <Password>{password}</Password> <ClientId>{clientId}</ClientId> <Type>Credit</Type> <OrderId>{request.OrderNumber}</OrderId> </CC5Request>"; var response = await client.PostAsync(request.BankParameters["verifyUrl"], new StringContent(requestXml, Encoding.UTF8, "text/xml")); string responseContent = await response.Content.ReadAsStringAsync(); var xmlDocument = new XmlDocument(); xmlDocument.LoadXml(responseContent); if (xmlDocument.SelectSingleNode("CC5Response/Response") == null || xmlDocument.SelectSingleNode("CC5Response/Response").InnerText != "Approved") { var errorMessage = xmlDocument.SelectSingleNode("CC5Response/ErrMsg")?.InnerText ?? string.Empty; if (string.IsNullOrEmpty(errorMessage)) { errorMessage = "Bankadan hata mesajı alınamadı."; } return(RefundPaymentResult.Failed(errorMessage)); } if (xmlDocument.SelectSingleNode("CC5Response/ProcReturnCode") == null || xmlDocument.SelectSingleNode("CC5Response/ProcReturnCode").InnerText != "00") { var errorMessage = xmlDocument.SelectSingleNode("CC5Response/ErrMsg")?.InnerText ?? string.Empty; if (string.IsNullOrEmpty(errorMessage)) { errorMessage = "Bankadan hata mesajı alınamadı."; } return(RefundPaymentResult.Failed(errorMessage)); } var transactionId = xmlDocument.SelectSingleNode("CC5Response/TransId")?.InnerText ?? string.Empty; return(RefundPaymentResult.Successed(transactionId, transactionId)); }
/// <summary> /// Refund. This method allows you make a refund. /// In this case a Refund button will be visible on the order details page in admin area. /// Note that an order should be paid, and SupportRefund or SupportPartiallyRefund property should return true. /// </summary> /// <param name="refundPaymentRequest"></param> /// <returns></returns> public RefundPaymentResult Refund(RefundPaymentRequest refundPaymentRequest) { ListResponse <OrderResponse> listResponse = _mollieOrderClient.GetOrderListAsync().Result; var mollieOrderId = ""; foreach (var orderItem in listResponse.Items) { if (orderItem.OrderNumber == refundPaymentRequest.Order.CustomOrderNumber) { mollieOrderId = orderItem.Id; } } if (string.IsNullOrEmpty(mollieOrderId)) { return new RefundPaymentResult { Errors = new[] { "Mollie OrderID is Null or Empty" } } } ; OrderResponse retrieveOrder = _mollieOrderClient.GetOrderAsync(mollieOrderId).Result; var orderlineList = new List <OrderLineDetails>(); foreach (var item in _orderService.GetOrderItems(refundPaymentRequest.Order.Id)) { foreach (var line in retrieveOrder.Lines) { orderlineList.Add(new OrderLineDetails() { Id = line.Id, Quantity = item.Quantity, Amount = new Amount(SelectCurrency().CurrencyCode, line.TotalAmount) }); } } OrderRefundRequest refundRequest = new OrderRefundRequest() { Lines = orderlineList }; OrderRefundResponse result = _mollieOrderClient.CreateOrderRefundAsync(mollieOrderId, refundRequest).Result; return(new RefundPaymentResult { NewPaymentStatus = refundPaymentRequest.IsPartialRefund ? PaymentStatus.PartiallyRefunded : PaymentStatus.Refunded }); }
internal RefundPaymentResult ExecuteRefund(RefundPaymentRequest refundPaymentRequest) { RefundPaymentResult result = new RefundPaymentResult(); Dictionary <string, Object> responseRefund = new Dictionary <string, Object>(); Dictionary <string, Object> response = new Dictionary <string, Object>(); if (refundPaymentRequest.IsPartialRefund) { responseRefund = ReturnRequest(refundPaymentRequest); } else { responseRefund = VoidRequest(refundPaymentRequest); } if (responseRefund.ContainsKey("VoidResponse")) { response = (Dictionary <string, Object>)responseRefund["VoidResponse"]; } if (responseRefund.ContainsKey("ReturnResponse")) { response = (Dictionary <string, Object>)responseRefund["ReturnResponse"]; } if (response.ContainsKey(TODOPAGO_STATUS_CODE)) { System.Int64 statusCode = (System.Int64)response[TODOPAGO_STATUS_CODE]; if (!statusCode.Equals(2011)) { // REFUND CON ERRORES String statusMessage = (String)response[TODOPAGO_STATUS_MESSAGE]; result.AddError(statusCode + " - " + statusMessage); } else { // REFUND BIEN if (refundPaymentRequest.IsPartialRefund && refundPaymentRequest.Order.RefundedAmount + refundPaymentRequest.AmountToRefund < refundPaymentRequest.Order.OrderTotal) { result.NewPaymentStatus = PaymentStatus.PartiallyRefunded; } else { result.NewPaymentStatus = PaymentStatus.Refunded; } } } return(result); }
public RefundPaymentResult Refund(RefundPaymentRequest refundPaymentRequest) { var result = new RefundPaymentResult(); try { var options = new StripeRefundCreateOptions(); var charge = _chargeService.Get(refundPaymentRequest.Order.CaptureTransactionId); var maximumRefund = charge.Amount - charge.AmountRefunded; options.Amount = (int)Math.Ceiling(refundPaymentRequest.AmountToRefund * 100); if (maximumRefund == 0 && !refundPaymentRequest.IsPartialRefund) //if it's a partial refund the user would not expect to see the order switch to the Refund status { result.NewPaymentStatus = PaymentStatus.Refunded; // this means it has been previously refunded from Stripe admin return(result); } if (options.Amount > maximumRefund) { if (maximumRefund > 0) { result.AddError("This charge has already been partially refunded. Maximum refund amount is: " + (decimal)maximumRefund / 100); } else { result.AddError("This charge has already been fully refunded."); } return(result); } refundPaymentRequest.IsPartialRefund = options.Amount != maximumRefund; _refundService.Create(refundPaymentRequest.Order.CaptureTransactionId, options); result.NewPaymentStatus = refundPaymentRequest.IsPartialRefund ? PaymentStatus.PartiallyRefunded : PaymentStatus.Refunded; return(result); } catch (StripeException exception) { if (!string.IsNullOrEmpty(exception.StripeError.Code)) { result.AddError(exception.StripeError.Message + " Error code: " + exception.StripeError.Code); } else { result.AddError(exception.StripeError.Message); } return(result); } }
/// <summary> /// Refunds a payment /// </summary> /// <param name="refundPaymentRequest">Request</param> /// <returns>Result</returns> public RefundPaymentResult Refund(RefundPaymentRequest refundPaymentRequest) { var result = new RefundPaymentResult(); string transactionId = refundPaymentRequest.Order.CaptureTransactionId; var req = new RefundTransactionReq(); req.RefundTransactionRequest = new RefundTransactionRequestType { Version = GetApiVersion(), TransactionID = transactionId }; if (refundPaymentRequest.IsPartialRefund) { req.RefundTransactionRequest.RefundType = RefundType.PARTIAL; req.RefundTransactionRequest.Amount = new BasicAmountType { currencyID = PaypalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId)), value = refundPaymentRequest.AmountToRefund.ToString() }; } else { req.RefundTransactionRequest.RefundType = RefundType.FULL; } var service = GetService(); RefundTransactionResponseType response = service.RefundTransaction(req); string error; bool success = PaypalHelper.CheckSuccess(response, out error); if (success) { result.NewPaymentStatus = (refundPaymentRequest.IsPartialRefund && refundPaymentRequest.Order.RefundedAmount + refundPaymentRequest.AmountToRefund < refundPaymentRequest.Order.OrderTotal) ? PaymentStatus.PartiallyRefunded : PaymentStatus.Refunded; //set refund transaction id for preventing refund twice _genericAttributeService.SaveAttribute(refundPaymentRequest.Order, "RefundTransactionId", response.RefundTransactionID); } else { result.AddError(error); } return(result); }
/// <summary> /// Refunds a payment /// </summary> /// <param name="refundPaymentRequest">Request</param> /// <returns>Result</returns> public RefundPaymentResult Refund(RefundPaymentRequest refundPaymentRequest) { var result = new RefundPaymentResult(); string transactionId = refundPaymentRequest.Order.CaptureTransactionId; var req = new RefundTransactionReq(); req.RefundTransactionRequest = new RefundTransactionRequestType(); //NOTE: Specify amount in partial refund req.RefundTransactionRequest.RefundType = RefundType.Full; req.RefundTransactionRequest.RefundTypeSpecified = true; req.RefundTransactionRequest.Version = GetApiVersion(); req.RefundTransactionRequest.TransactionID = transactionId; using (var service1 = new PayPalAPISoapBinding()) { if (!_paypalDirectPaymentSettings.UseSandbox) { service1.Url = "https://api-3t.paypal.com/2.0/"; } else { service1.Url = "https://api-3t.sandbox.paypal.com/2.0/"; } service1.RequesterCredentials = new CustomSecurityHeaderType(); service1.RequesterCredentials.Credentials = new UserIdPasswordType(); service1.RequesterCredentials.Credentials.Username = _paypalDirectPaymentSettings.ApiAccountName; service1.RequesterCredentials.Credentials.Password = _paypalDirectPaymentSettings.ApiAccountPassword; service1.RequesterCredentials.Credentials.Signature = _paypalDirectPaymentSettings.Signature; service1.RequesterCredentials.Credentials.Subject = ""; RefundTransactionResponseType response = service1.RefundTransaction(req); string error = string.Empty; bool Success = PaypalHelper.CheckSuccess(response, out error); if (Success) { result.NewPaymentStatus = PaymentStatus.Refunded; //cancelPaymentResult.RefundTransactionID = response.RefundTransactionID; } else { result.AddError(error); } } return(result); }
public void Refund_remaining_two_lines() { var refundRemainingRequest = new RefundPaymentRequest( TestState.FinalizeAuthorizationResponse.TransactionId, TestState.CreateOrderResponse.OrderId, TestState.CreateOrderRequest.LineItems[1].TotalLineAmount + TestState.CreateOrderRequest.LineItems[2].TotalLineAmount) .AddLineItem(TestState.CreateOrderRequest.LineItems[1]) .AddLineItem(TestState.CreateOrderRequest.LineItems[2]); var refundRemainingResponse = Client.RefundPayment(refundRemainingRequest); refundRemainingResponse.ShouldBe().RefundedInFull(TestState.CreateOrderRequest.TotalAmount); }
//////////////// Payment Refund methods ///////////// private void PaymentRefundButton_Click(object sender, EventArgs e) { RefundPaymentRequest request = new RefundPaymentRequest(); if (OrderPaymentsView.SelectedItems.Count == 1) { POSPayment payment = ((POSPayment)OrderPaymentsView.SelectedItems[0].Tag); request.PaymentId = payment.PaymentID; POSOrder order = (POSOrder)OrdersListView.SelectedItems[0].Tag; request.OrderId = payment.OrderID; TempObjectMap.Add(payment.OrderID, order); cloverConnector.RefundPayment(request); } }
/// <summary> /// Refunds a payment /// </summary> /// <param name="refundPaymentRequest">Request</param> /// <returns>Result</returns> public RefundPaymentResult Refund(RefundPaymentRequest refundPaymentRequest) { var result = new RefundPaymentResult(); var codes = refundPaymentRequest.Order.CaptureTransactionId == null ? refundPaymentRequest.Order.AuthorizationTransactionCode.Split(',') : refundPaymentRequest.Order.CaptureTransactionId.Split(','); _httpClient.DefaultRequestHeaders.Add("developer-id", _paySafePaymentSettings.DeveloperId); _httpClient.DefaultRequestHeaders.Add("user-id", _paySafePaymentSettings.UserId); _httpClient.DefaultRequestHeaders.Add("user-api-key", _paySafePaymentSettings.UserApiKey); var json = JsonConvert.SerializeObject(new { transaction = new Dictionary <string, string> { { "action", "refund" }, { "payment_method", "cc" }, { "previous_transaction_id", codes[0] }, { "transaction_amount", refundPaymentRequest.AmountToRefund.ToString("0.00", CultureInfo.InvariantCulture) }, { "location_id", _paySafePaymentSettings.LocationId } } }); var data = new StringContent(json, Encoding.UTF8, "application/json"); try { var response = _httpClient.PostAsync(GetUrl(), data).Result; var paySafeResponse = JsonConvert.DeserializeObject <PaySafeResponse>(response.Content.ReadAsStringAsync().Result); var transactionResult = paySafeResponse.Transaction; if (response.IsSuccessStatusCode) { var refundedTotalAmount = refundPaymentRequest.AmountToRefund + refundPaymentRequest.Order.RefundedAmount; var isOrderFullyRefunded = refundedTotalAmount == refundPaymentRequest.Order.OrderTotal; result.NewPaymentStatus = isOrderFullyRefunded ? PaymentStatus.Refunded : PaymentStatus.PartiallyRefunded; } } catch (Exception exception) { _logger.Error("PaySafe Error", exception); result.AddError("Exception Occurred: " + exception.Message); return(result); } return(result); }
public void RefundPayment(HttpListenerContext context) { try { RefundPaymentRequest message = ParseRequest <RefundPaymentRequest>(context); GetServer.CloverConnector.RefundPayment(message); this.SendTextResponse(context, ""); } catch (Exception e) { context.Response.StatusCode = 400; context.Response.StatusDescription = e.Message; this.SendTextResponse(context, "error processing request"); } }
/// <summary> /// Refunds a payment /// </summary> /// <param name="refundPaymentRequest">Request</param> /// <returns>Result</returns> public RefundPaymentResult Refund(RefundPaymentRequest refundPaymentRequest) { if (refundPaymentRequest == null) { throw new ArgumentNullException(nameof(refundPaymentRequest)); } var refundRequest = new CreateRefundRequest { PaymentId = Guid.Parse(refundPaymentRequest.Order.CaptureTransactionId), Amount = (int)(refundPaymentRequest.AmountToRefund * 100) }; try { var refundResponse = _refundApi.CreateRefundAsync(refundRequest).GetAwaiter().GetResult(); if (refundResponse == null) { return new RefundPaymentResult { Errors = new[] { "No refund response" } } } ; var refundIds = _genericAttributeService.GetAttribute <List <string> >(refundPaymentRequest.Order, Defaults.RefundIdAttributeName) ?? new List <string>(); var refundId = refundResponse.Id.ToString(); if (!refundIds.Contains(refundId)) { refundIds.Add(refundId); } _genericAttributeService.SaveAttribute(refundPaymentRequest.Order, Defaults.RefundIdAttributeName, refundIds); return(new RefundPaymentResult { NewPaymentStatus = refundPaymentRequest.IsPartialRefund ? Core.Domain.Payments.PaymentStatus.PartiallyRefunded : Core.Domain.Payments.PaymentStatus.Refunded }); } catch (ApiException exception) { _logger.Error($"{Defaults.SystemName}: {exception.Message}", exception); return(new RefundPaymentResult { Errors = new[] { exception.Message } }); } }
public virtual async Task <IList <string> > PartiallyRefundAsync(Order order, decimal amountToRefund) { Guard.NotNull(order, nameof(order)); if (!await CanPartiallyRefundAsync(order, amountToRefund)) { throw new SmartException(T("Order.CannotPartialRefund")); } RefundPaymentResult result = null; try { var request = new RefundPaymentRequest { Order = order, AmountToRefund = new Money(amountToRefund, _primaryCurrency), IsPartialRefund = true }; result = await _paymentService.RefundAsync(request); if (result.Success) { var totalAmountRefunded = order.RefundedAmount + amountToRefund; order.RefundedAmount = totalAmountRefunded; order.PaymentStatus = result.NewPaymentStatus; order.AddOrderNote(T("Admin.OrderNotice.OrderPartiallyRefunded", request.AmountToRefund.ToString(true))); // INFO: CheckOrderStatus performs commit. await CheckOrderStatusAsync(order); } } catch (Exception ex) { result ??= new(); result.Errors.Add(ex.ToAllMessages()); } if (result.Errors.Any()) { ProcessErrors(order, result.Errors, "Admin.OrderNotice.OrderPartiallyRefundError"); await _db.SaveChangesAsync(); } return(result.Errors); }
public async Task <RefundPaymentResult> RefundRequest(RefundPaymentRequest request) { string mbrId = request.BankParameters["mbrId"]; //Mağaza numarası string merchantId = request.BankParameters["merchantId"]; //Mağaza numarası string userCode = request.BankParameters["userCode"]; // string userPass = request.BankParameters["userPass"]; //Mağaza anahtarı string txnType = request.BankParameters["txnType"]; //İşlem tipi string secureType = request.BankParameters["secureType"]; string totalAmount = request.TotalAmount.ToString(new CultureInfo("en-US")); string requestXml = $@"<?xml version=""1.0"" encoding=""utf-8"" standalone=""yes""?> <PayforIade> <MbrId>{mbrId}</MbrId> <MerchantID>{merchantId}</MerchantID> <UserCode>{userCode}</UserCode> <UserPass>{userPass}</UserPass> <OrgOrderId>{request.OrderNumber}</OrgOrderId> <SecureType>NonSecure</SecureType> <TxnType>Refund</TxnType> <PurchAmount>{totalAmount}</PurchAmount> <Currency>{request.CurrencyIsoCode}</Currency> <Lang>{request.LanguageIsoCode.ToUpper()}</Lang> </PayforIade>"; var response = await client.PostAsync(request.BankParameters["verifyUrl"], new StringContent(requestXml, Encoding.UTF8, "text/xml")); string responseContent = await response.Content.ReadAsStringAsync(); var xmlDocument = new XmlDocument(); xmlDocument.LoadXml(responseContent); //TODO Finansbank response //if (xmlDocument.SelectSingleNode("VposResponse/ResultCode") == null || // xmlDocument.SelectSingleNode("VposResponse/ResultCode").InnerText != "0000") //{ // string errorMessage = xmlDocument.SelectSingleNode("VposResponse/ResultDetail")?.InnerText ?? string.Empty; // if (string.IsNullOrEmpty(errorMessage)) // errorMessage = "Bankadan hata mesajı alınamadı."; // return RefundPaymentResult.Failed(errorMessage); //} var transactionId = xmlDocument.SelectSingleNode("VposResponse/TransactionId")?.InnerText; return(RefundPaymentResult.Successed(transactionId, transactionId)); }
/// <summary> /// Refunds a payment /// </summary> /// <param name="refundPaymentRequest">Request</param> /// <returns>Result</returns> public RefundPaymentResult Refund(RefundPaymentRequest refundPaymentRequest) { var result = new RefundPaymentResult(); var refundResult = _sagePayServerWorkflowService.RefundTransaction(refundPaymentRequest.Order.OrderGuid.ToString(), refundPaymentRequest.Order.OrderTotal, refundPaymentRequest.Order.CustomerCurrencyCode); if (!refundResult.Success) { result.AddError(refundResult.Message); } else { result.NewPaymentStatus = PaymentStatus.Refunded; } return(result); }
/// <summary> /// Refunds a payment that was previously captured (settled). You can expect partial refunds. /// </summary> /// <param name="refundPaymentRequest"></param> /// <returns></returns> public async Task <RefundPaymentResponse> RefundPayment(RefundPaymentRequest refundPaymentRequest, string publicKey, string privateKey) { bool isLive = !refundPaymentRequest.sandboxMode; // await this.GetIsLiveSetting(); CreatePaymentRequest paymentRequest = await this._paymentRequestRepository.GetPaymentRequestAsync(refundPaymentRequest.paymentId); // Get Affirm id from storage refundPaymentRequest.authorizationId = paymentRequest.transactionId; int amount = decimal.ToInt32(refundPaymentRequest.value * 100); IAffirmAPI affirmAPI = new AffirmAPI(_httpContextAccessor, _httpClient, isLive, _context); dynamic affirmResponse = await affirmAPI.RefundAsync(publicKey, privateKey, refundPaymentRequest.authorizationId, amount); RefundPaymentResponse refundPaymentResponse = new RefundPaymentResponse { paymentId = refundPaymentRequest.paymentId, refundId = affirmResponse.reference_id ?? affirmResponse.id, value = affirmResponse.amount == null ? 0m : (decimal)affirmResponse.amount / 100m, code = affirmResponse.type ?? affirmResponse.Error.Code, message = affirmResponse.id != null ? $"Id:{affirmResponse.id} Fee={(affirmResponse.fee_refunded > 0 ? (decimal)affirmResponse.fee_refunded / 100m : 0):F2}" : affirmResponse.Error.Message, requestId = refundPaymentRequest.requestId }; if (refundPaymentRequest.authorizationId.StartsWith(AffirmConstants.KatapultIdPrefix)) { // Need to get details from Katapult VtexSettings vtexSettings = await _paymentRequestRepository.GetAppSettings(); if (vtexSettings.enableKatapult) { KatapultFunding katapultResponse = await affirmAPI.KatapultFundingAsync(vtexSettings.katapultPrivateToken); if (katapultResponse != null) { FundingObject fundingObject = katapultResponse.FundingReport.FundingObjects.Where(f => f.OrderId.Equals(paymentRequest.orderId)).FirstOrDefault(); if (fundingObject != null) { refundPaymentResponse.message = $"Id:{affirmResponse.id} Fee={(fundingObject.Discount):F2}"; _context.Vtex.Logger.Info("RefundPayment", null, $"RefundPayment {refundPaymentResponse}"); } } } } return(refundPaymentResponse); }
private Dictionary <string, Object> ReturnRequest(RefundPaymentRequest refundPaymentRequest) { Dictionary <string, string> refundParams = new Dictionary <string, string>(); Dictionary <string, Object> responseRefund = new Dictionary <string, Object>(); var amountToRefund = (refundPaymentRequest.AmountToRefund / refundPaymentRequest.Order.OrderTotal) * (refundPaymentRequest.Order.OrderTotal - refundPaymentRequest.Order.OrderTax); var orderTotal = Math.Round(amountToRefund, 2); String amount = orderTotal.ToString("0.00", CultureInfo.InvariantCulture); refundParams = GenerateReturnRequestParams(refundPaymentRequest.Order.Id, amount); _logger.Information("TodoPago ParamsRefund : " + todoPagoBusinessService.serealizar(refundParams)); responseRefund = this.connector.ReturnRequest(refundParams); _logger.Information("TodoPago resultRefund : " + todoPagoBusinessService.serealizarRefund(responseRefund)); return(responseRefund); }
/// <summary> /// Refunds a payment /// </summary> /// <param name="refundPaymentRequest">Request</param> /// <returns>Result</returns> public RefundPaymentResult Refund(RefundPaymentRequest refundPaymentRequest) { var result = new RefundPaymentResult(); try { var apiContext = PaypalHelper.GetApiContext(_paypalDirectPaymentSettings); var capture = PayPal.Api.Capture.Get(apiContext, refundPaymentRequest.Order.CaptureTransactionId); var currency = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId); var refund = new Refund { amount = new Amount { total = refundPaymentRequest.AmountToRefund.ToString("N", new CultureInfo("en-US")), currency = currency != null ? currency.CurrencyCode : null } }; capture.Refund(apiContext, refund); capture = PayPal.Api.Capture.Get(apiContext, refundPaymentRequest.Order.CaptureTransactionId); result.NewPaymentStatus = GetPaymentStatus(capture.state); } catch (PayPal.PayPalException exc) { if (exc is PayPal.ConnectionException) { var error = JsonFormatter.ConvertFromJson <Error>((exc as PayPal.ConnectionException).Response); if (error != null) { result.AddError(string.Format("PayPal error: {0} ({1})", error.message, error.name)); if (error.details != null) { error.details.ForEach(x => result.AddError(string.Format("{0} {1}", x.field, x.issue))); } } } //if there are not the specific errors add exception message if (result.Success) { result.AddError(exc.InnerException != null ? exc.InnerException.Message : exc.Message); } } return(result); }
/// <summary> /// Refunds a payment /// </summary> /// <param name="refundPaymentRequest">Request</param> /// <returns>Result</returns> public RefundPaymentResult Refund(RefundPaymentRequest refundPaymentRequest) { var customSecurityHeaderType = _payPalSecurityService.GetRequesterCredentials(); using var payPalApiInterfaceClient = _payPalInterfaceService.GetService(); var response = payPalApiInterfaceClient.RefundTransaction(ref customSecurityHeaderType, _payPalRequestService.GetRefundTransactionRequest(refundPaymentRequest)); return(response.HandleResponse(new RefundPaymentResult(), (paymentResult, type) => paymentResult.NewPaymentStatus = refundPaymentRequest.IsPartialRefund ? PaymentStatus.PartiallyRefunded : PaymentStatus.Refunded, (paymentResult, type) => response.Errors.AddErrors(paymentResult.AddError), refundPaymentRequest.Order.OrderGuid)); }
public RefundPaymentResult Refund(RefundPaymentRequest refundPaymentRequest) { var refund = refundPaymentRequest.CreateRefund(this._stripePaymentSettings, this._currencySettings, this._currencyService); if (refund.GetStatus() != StripeRefundStatus.Succeeded) { return(new RefundPaymentResult { Errors = new[] { $"Refund is {refund.Status}" }.ToList() }); } else { return(new RefundPaymentResult { NewPaymentStatus = refundPaymentRequest.IsPartialRefund ? PaymentStatus.PartiallyRefunded : PaymentStatus.Refunded }); } }
public RefundPaymentResponse Process(RefundPaymentRequest request) { Transaction tx = new Transaction(); tx.TestMode = request.Test; tx.SetRequestParameter("VPSProtocol", "3.00"); tx.SetRequestParameter("TxType", "REFUND"); tx.SetRequestParameter("Vendor", request.Vendor); tx.SetRequestParameter("VendorTxCode", request.VendorTxCode); tx.SetRequestParameter("Amount", request.Amount.ToString()); tx.SetRequestParameter("Currency", request.Currency); tx.SetRequestParameter("Description", request.Description); tx.SetRequestParameter("RelatedVPSTxId", request.RelatedVPSTxId); tx.SetRequestParameter("RelatedVendorTxCode", request.RelatedVendorTxCode); tx.SetRequestParameter("RelatedSecurityKey", request.RelatedSecurityKey); tx.SetRequestParameter("RelatedTxAuthNo", request.RelatedTxAuthNo); tx.SendRefund(); // Receive Response var response = new RefundPaymentResponse(); response.VPSProtocol = tx.GetResponseParameter("VPSProtocol"); response.TxType = "REFUND"; response.Status = tx.GetResponseParameter("Status"); response.StatusDetail = tx.GetResponseParameter("StatusDetail"); response.VpsTxId = tx.GetResponseParameter("VPSTxID"); response.TxAuthNo = tx.GetResponseParameter("TxAuthNo"); if (!String.IsNullOrEmpty(response.StatusDetail)) response.StatusDetail = response.StatusDetail.Replace("'", "`"); return response; }
public override ApiInfo RefundPayment( Order order, IDictionary<string, string> settings ) { ApiInfo apiInfo = null; try { order.MustNotBeNull( "order" ); settings.MustNotBeNull( "settings" ); RefundPaymentRequest request = new RefundPaymentRequest( order.TransactionInformation.TransactionId, order.TransactionInformation.AmountAuthorized.Value ); RefundPaymentResponse response = GetClient( settings ).RefundPayment( request ); apiInfo = new ApiInfo( response.TransactionId, PaymentState.Refunded ); } catch ( Exception exp ) { LoggingService.Instance.Error<Paynova>( "Paynova(" + order.OrderNumber + ") - Refund payment", exp ); } return apiInfo; }
public RefundPaymentResponse Refund(RefundPaymentRequest refundPaymentRequest) { var paymentMethod = GetPaymentMethodByKey(refundPaymentRequest.Order.PaymentMethod); return paymentMethod.Refund(refundPaymentRequest); }
public RefundPaymentResponse Refund(RefundPaymentRequest refundPaymentRequest) { var result = new RefundPaymentResponse(); result.AddError("Refund method not supported"); return result; }