trabajando en devoluciones

This commit is contained in:
2025-11-05 15:09:26 +01:00
parent ed32f773a4
commit a4443763d8
13 changed files with 330 additions and 124 deletions

View File

@ -8,6 +8,11 @@ import sis.redsys.api.ApiMacSha256;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;
@ -18,6 +23,10 @@ import java.util.Objects;
public class RedsysService {
// ---------- CONFIG ----------
@Value("${redsys.url}")
private String url;
@Value("${redsys.refund.url}")
private String urlRefund;
@Value("${redsys.merchant-code}")
private String merchantCode;
@Value("${redsys.terminal}")
@ -37,6 +46,8 @@ public class RedsysService {
@Value("${redsys.environment}")
private String env;
private final HttpClient httpClient = HttpClient.newHttpClient();
// ---------- RECORDS ----------
// Pedido a Redsys
public record PaymentRequest(String order, long amountCents, String description, Long cartId) {
@ -89,9 +100,11 @@ public class RedsysService {
String merchantParameters = api.createMerchantParameters();
String signature = api.createMerchantSignature(secretKeyBase64);
String action = "test".equalsIgnoreCase(env)
? "https://sis-t.redsys.es:25443/sis/realizarPago"
: "https://sis.redsys.es/sis/realizarPago";
String action = url;
/*
* ? "https://sis-t.redsys.es:25443/sis/realizarPago"
* : "https://sis.redsys.es/sis/realizarPago";
*/
return new FormPayload(action, "HMAC_SHA256_V1", merchantParameters, signature);
}
@ -231,4 +244,84 @@ public class RedsysService {
}
}
}
/**
* Solicita a Redsys una devolución (TransactionType = 3)
*
* @param order El mismo Ds_Merchant_Order que se usó en el cobro.
* @param amountCents Importe en céntimos a devolver.
* @return gatewayRefundId (p.ej. Ds_AuthorisationCode o Ds_Order)
*/
public String requestRefund(String order, long amountCents) throws Exception {
ApiMacSha256 api = new ApiMacSha256();
// Montar parámetros para el refund
api.setParameter("DS_MERCHANT_MERCHANTCODE", merchantCode);
api.setParameter("DS_MERCHANT_TERMINAL", terminal);
api.setParameter("DS_MERCHANT_ORDER", order);
api.setParameter("DS_MERCHANT_AMOUNT", String.valueOf(amountCents));
api.setParameter("DS_MERCHANT_CURRENCY", currency);
api.setParameter("DS_MERCHANT_TRANSACTIONTYPE", "3"); // 3 = devolución
api.setParameter("DS_MERCHANT_MERCHANTURL", "");
api.setParameter("DS_MERCHANT_URLOK", "");
api.setParameter("DS_MERCHANT_URLKO", "");
// Crear parámetros y firma (como en tu PHP)
String merchantParameters = api.createMerchantParameters();
String signature = api.createMerchantSignature(secretKeyBase64);
// Montar el JSON para Redsys REST
String json = """
{
"Ds_MerchantParameters": "%s",
"Ds_Signature": "%s",
"Ds_SignatureVersion": "HMAC_SHA256_V1"
}
""".formatted(merchantParameters, signature);
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(urlRefund))
.header("Content-Type", "application/json; charset=UTF-8")
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("### Redsys refund REST request:\n" + json);
System.out.println("### HTTP " + response.statusCode());
System.out.println("### Redsys refund REST response:\n" + response.body());
if (response.statusCode() / 100 != 2)
throw new IllegalStateException("HTTP error Redsys refund: " + response.statusCode());
if (response.body() == null || response.body().isBlank())
throw new IllegalStateException("Respuesta vacía de Redsys refund REST");
// Parsear la respuesta JSON
Map<String, Object> respMap = MAPPER.readValue(response.body(), new TypeReference<>() {
});
// Redsys puede devolver "Ds_MerchantParameters" o "errorCode"
if (respMap.containsKey("errorCode")) {
throw new IllegalStateException("Error Redsys refund: " + respMap.get("errorCode"));
}
String dsMerchantParametersResp = (String) respMap.get("Ds_MerchantParameters");
if (dsMerchantParametersResp == null) {
throw new IllegalStateException("Respuesta Redsys refund sin Ds_MerchantParameters");
}
// Decodificar MerchantParameters de la respuesta
Map<String, Object> decoded = decodeMerchantParametersToMap(dsMerchantParametersResp);
System.out.println("### Redsys refund decoded response:\n" + decoded);
String dsResponse = String.valueOf(decoded.get("Ds_Response"));
if (!"0900".equals(dsResponse)) {
throw new IllegalStateException("Devolución rechazada, Ds_Response=" + dsResponse);
}
return String.valueOf(decoded.getOrDefault("Ds_AuthorisationCode", order));
}
}