diff --git a/README.md b/README.md index f9d346d..629c74a 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ Luego agregar la dependencia: ``` -## Configuracion +## Configuración Para empezar a enviar peticiones al API de Culqi debes configurar tu llave pública (pk), llave privada (sk). Para habilitar encriptación de payload debes configurar tu rsa_id y rsa_public_key. @@ -113,6 +113,18 @@ protected Map createCharge() throws Exception { } ``` +Para realizar un cargo recurrente, puedes utilizar el siguiente código: + +```java +protected Map createCharge() throws Exception { + String source_id = createToken().get("id").toString(); + Map customHeaders = new HashMap(); + customHeaders.put("X-Charge-Channel", "recurrent"); + + return init().charge.create(jsondata.jsonCharge(source_id), customHeaders); +} +``` + ### Crear Devolución Solicita la devolución de las compras de tus clientes (parcial o total) de forma gratuita a través del API y CulqiPanel. @@ -265,6 +277,118 @@ Luego agregas la siguiente dependencia en el pom.xml - [Jackson Core Databind](https://github.com/FasterXML/jackson-databind/wiki) - [Wiki](https://github.com/culqi/culqi-java/wiki) +### Instalar Java +Descarga Spring Tools Suite 4-4.21.0 archivo del siguiente link: + +```bash + https://cdn.spring.io/spring-tools/release/STS4/4.21.0.RELEASE/dist/e4.30/spring-tool-suite-4-4.21.0.RELEASE-e4.30.0-linux.gtk.x86_64.tar.gz +``` + +### Instalar jdk (Kit de Desarrollo de Java) +Asegúrate de tener instalado el JDK 8 mediante los siguientes comandos: + +```bash +sudo apt-get update +sudo apt-get install openjdk-8-jdk +``` +### Configurar Variables de Entorno para Java y Maven +Edita el archivo .bashrc con el siguiente comando: + +```bash + #Abre el archivo .bashrc + nano ~/.bashrc +``` +Añade las siguientes líneas al final del archivo: + +```bash + #Agrega las siguientes líneas al final del archivo: + JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64 + M2_HOME=/usr/share/maven + PATH=$PATH:$JAVA_HOME/bin:$M2_HOME/bin +``` +Guarda los cambios y cierra el editor (Ctrl + o >> Enter >> Ctrl + x). + +### Instalar Maven +Instala Maven con el siguiente comando + +```bash +sudo apt-get install maven +``` + + +### Como abrir el archvio SDK + +Abre Spring Tools Suite y selecciona: +```bash + FILE >> IMPORT >> MAVEN >> EXISTING MAVEN PROJECTS +``` + +### Instalar Dependencias +Haz clic derecho en la carpeta raíz del proyecto y selecciona: + +```bash + RUN AS >> MAVEN CLEAN + RUN AS >> MAVEN INSTALL +``` + +### Ejecutar Tests +Haz clic derecho en la carpeta src/test/java y selecciona: + +```bash + RUN AS >> JUnit Test +``` +Espera a que se ejecuten todas las pruebas unitarias y, luego, ejecuta cada prueba individualmente según las necesidades. + +```bash +CulqiCreateTest: + test05_createPlan + test08_createSubscription + +CulqiDeleteTest: + test01_deleteSubscription + test02_deletePlan + +CulqiGetTest: + test06_findPlan + test07_findSubscription + +CulqiAllTest: + test04_allPlan + test06_allSubscriptions +``` +Click derecho en el nombre del test_0** >> RUN + +### Donde Encontrar los ejemplos para Pruebas +Dentro de la estructura del proyecto, encontrarás ejemplos de pruebas que puedes utilizar para verificar el funcionamiento del SDK. Sigue estos pasos para acceder y ejecutar los ejemplos: + +# Ubicación de los Ejemplos: +* Haz clic derecho en la carpeta src/test/java. +* Abre el archivo CulqiCRUD.java. +* En la linea 27 puedes configurar el secreto: + +```bash + culqi.secret_key = "sk_live_************"; +``` + +* Haz clic derecho en la carpeta src/test/java. +* Abre el archivo JsonData.java. + +* Ejemplo de JSON: +En el archivo JsonData.java, encontrarás ejemplos de datos en formato JSON que se utilizan en las pruebas. Puedes modificar estos datos según tus necesidades. + +```bash +php examples/plan/02-create-plan.php + Crear Plan: jsonPlan + Actualizar Plan: jsonUpdatePlan + All Plan: jsonPlanFilter + + Crear Subscription: jsonSubscription + Actualizar Subscription: jsonUpdateSubscription + All Subscription: jsonListSubscriptions +``` +Modifica estos ejemplos según tus necesidades y asegúrate de tener configuradas correctamente tus credenciales de Culqi antes de ejecutar las pruebas. + + ## Changelog Todos los cambios en las versiones de esta biblioteca están listados en [CHANGELOG](CHANGELOG). diff --git a/src/main/java/com/culqi/apioperation/ObjectResult.java b/src/main/java/com/culqi/apioperation/ObjectResult.java index 77d9a0d..9110265 100644 --- a/src/main/java/com/culqi/apioperation/ObjectResult.java +++ b/src/main/java/com/culqi/apioperation/ObjectResult.java @@ -27,13 +27,32 @@ public ResponseCulqi create(Map body, String url) throws Excepti return response; } + public ResponseCulqi create (Map body, String url, Map customHeaders) throws Exception { + String jsonData = mapper.writeValueAsString(body); + ResponseCulqi response = new ResponseHelper().create(url, jsonData, customHeaders); + return response; + } + public ResponseCulqi create(Map body, String url, String rsaPublicKey, String rsaId ) throws Exception { String jsonData = mapper.writeValueAsString(body); EncryptAESRSA encryptAESRSA = new EncryptAESRSA(); jsonData = encryptAESRSA.getJsonEncryptAESRSA(jsonData, rsaPublicKey); - ResponseCulqi response = new ResponseHelper().create(url, jsonData, rsaId);System.out.println(jsonData); + ResponseCulqi response = new ResponseHelper().create(url, jsonData, rsaId); + System.out.println(jsonData); + System.out.println(response.getStatusCode()); + return response; + } + + public ResponseCulqi create(Map body, String url, String rsaPublicKey, String rsaId, Map customHeaders ) throws Exception { + String jsonData = mapper.writeValueAsString(body); + + EncryptAESRSA encryptAESRSA = new EncryptAESRSA(); + jsonData = encryptAESRSA.getJsonEncryptAESRSA(jsonData, rsaPublicKey); + + ResponseCulqi response = new ResponseHelper().create(url, jsonData, rsaId, customHeaders); + System.out.println(jsonData); System.out.println(response.getStatusCode()); return response; } diff --git a/src/main/java/com/culqi/apioperation/ResponseHelper.java b/src/main/java/com/culqi/apioperation/ResponseHelper.java index 4eb82ce..a162626 100644 --- a/src/main/java/com/culqi/apioperation/ResponseHelper.java +++ b/src/main/java/com/culqi/apioperation/ResponseHelper.java @@ -32,7 +32,16 @@ public ResponseCulqi list(String url, String params) { try { HttpUrl.Builder builder = new HttpUrl.Builder(); - builder.scheme("https").host(Config.DOMAIN).addPathSegment("v2").addPathSegment(url); + + builder.scheme("https").host(Config.DOMAIN).addPathSegment("v2"); + if (url.contains("plans")) { + builder.addPathSegment("recurrent").addPathSegment("plans"); + } else if (url.contains("subscriptions")) { + builder.addPathSegment("recurrent").addPathSegment("subscriptions"); + } else { + builder.scheme("https").host(Config.DOMAIN).addPathSegment("v2").addPathSegment(url); + } + if (params != null) { HashMap map = new HashMap(); String[] pairs = params.replace("{", "").replace("}", "").split(","); @@ -72,7 +81,8 @@ public ResponseCulqi list(String url, String params) { return responseCulqi(GENERIC_ERROR, result); } - public ResponseCulqi create(String url, String jsonData) {System.out.println("jsonData "+jsonData); + public ResponseCulqi create(String url, String jsonData) { + System.out.println("jsonData "+jsonData); String result = ""; try { String api_key = url.contains("tokens") || url.contains("confirm") ? Culqi.public_key : Culqi.secret_key; @@ -81,6 +91,7 @@ public ResponseCulqi list(String url, String params) { env = Config.X_CULQI_ENV_LIVE; } String base_url = url.contains("tokens") ? config.API_SECURE : config.API_BASE; + url = (url.contains("plans") || url.contains("subscriptions")) ? url + "create" : url; RequestBody body = RequestBody.create(JSON, jsonData); Request request = new Request.Builder() .url(base_url+url) @@ -99,6 +110,35 @@ public ResponseCulqi list(String url, String params) { return responseCulqi(GENERIC_ERROR, result); } + public ResponseCulqi create(String url, String jsonData, Map customHeaders) { + String result = ""; + try { + String api_key = url.contains("tokens") || url.contains("confirm") ? Culqi.public_key : Culqi.secret_key; + String env = Config.X_CULQI_ENV_TEST; + if(api_key.contains("live")) { + env = Config.X_CULQI_ENV_LIVE; + } + String base_url = url.contains("tokens") ? config.API_SECURE : config.API_BASE; + url = (url.contains("plans") || url.contains("subscriptions")) ? url + "create" : url; + RequestBody body = RequestBody.create(JSON, jsonData); + Request.Builder builder = new Request.Builder() + .url(base_url+url) + .header("Authorization","Bearer " + api_key) + .header("x-culqi-env", env) + .header("x-culqi-client", Config.X_CULQI_CLIENT) + .header("x-culqi-client-version", Config.X_CULQI_CLIENT_VERSION) + .header("x-api-version", Config.X_API_VERSION) + .post(body); + builder = addCustomHeadersToRequest(customHeaders, builder); + Request request = builder.build(); + Response response = client.newCall(request).execute(); + return responseCulqi(response.code(), response.body().string()); + } catch (IOException e) { + result = exceptionError(); + } + return responseCulqi(GENERIC_ERROR, result); + } + public ResponseCulqi create(String url, String jsonData, String rsaId) { String result = ""; try { @@ -108,6 +148,7 @@ public ResponseCulqi create(String url, String jsonData, String rsaId) { env = Config.X_CULQI_ENV_LIVE; } String base_url = url.contains("tokens") ? config.API_SECURE : config.API_BASE; + url = (url.contains("plans") || url.contains("subscriptions")) ? url + "create" : url; RequestBody body = RequestBody.create(JSON, jsonData); Request request = new Request.Builder() .url(base_url+url) @@ -127,6 +168,36 @@ public ResponseCulqi create(String url, String jsonData, String rsaId) { return responseCulqi(GENERIC_ERROR, result); } + public ResponseCulqi create(String url, String jsonData, String rsaId, Map customHeaders) { + String result = ""; + try { + String api_key = url.contains("tokens") || url.contains("confirm") ? Culqi.public_key : Culqi.secret_key; + String env = Config.X_CULQI_ENV_TEST; + if(api_key.contains("live")) { + env = Config.X_CULQI_ENV_LIVE; + } + String base_url = url.contains("tokens") ? config.API_SECURE : config.API_BASE; + url = (url.contains("plans") || url.contains("subscriptions")) ? url + "create" : url; + RequestBody body = RequestBody.create(JSON, jsonData); + Request.Builder builder = new Request.Builder() + .url(base_url+url) + .header("Authorization","Bearer " + api_key) + .header("x-culqi-rsa-id", rsaId) + .header("x-culqi-env", env) + .header("x-culqi-client", Config.X_CULQI_CLIENT) + .header("x-culqi-client-version", Config.X_CULQI_CLIENT_VERSION) + .header("x-api-version", Config.X_API_VERSION) + .post(body); + builder = addCustomHeadersToRequest(customHeaders, builder); + Request request = builder.build(); + Response response = client.newCall(request).execute(); + return responseCulqi(response.code(), response.body().string()); + } catch (IOException e) { + result = exceptionError(); + } + return responseCulqi(GENERIC_ERROR, result); + } + public ResponseCulqi update(String url, String jsonData, String id) { String result = ""; try { @@ -256,6 +327,14 @@ public ResponseCulqi confirm(String url, String id) throws Exception { return responseCulqi(GENERIC_ERROR, result); } + private Request.Builder addCustomHeadersToRequest(Map customHeaders, Request.Builder builder) { + for (Map.Entry entry : customHeaders.entrySet()) { + System.out.println("Adding header '" + entry.getKey() + "' with value = " + entry.getValue()); + builder.header(entry.getKey(), entry.getValue()); + } + return builder; + } + private String exceptionError() { String result = ""; Map errorResponse = new HashMap(); diff --git a/src/main/java/com/culqi/apioperation/service/Generic.java b/src/main/java/com/culqi/apioperation/service/Generic.java index c0a1c03..7e5f875 100644 --- a/src/main/java/com/culqi/apioperation/service/Generic.java +++ b/src/main/java/com/culqi/apioperation/service/Generic.java @@ -30,7 +30,13 @@ public ResponseCulqi list(Map params) throws Exception { response.setBody(mapper.writeValueAsString(validationResponse)); return response; } - return new ObjectResult().list(this.URL.replace("/",""), params); + + String url = this.URL; + if (!url.contains("plans") || !url.contains("subscriptions")) { + url.replace("/", ""); + } + + return new ObjectResult().list(url, params); } public ResponseCulqi list() throws Exception { @@ -48,10 +54,25 @@ public ResponseCulqi create(Map body) throws Exception { return new ObjectResult().create(body, this.URL); } + public ResponseCulqi create(Map body, Map customHeaders ) throws Exception { + Map validationResponse = verifyClassValidationCreate(body, this.URL); + if (validationResponse != null) { + ResponseCulqi response = new ResponseCulqi(); + response.setStatusCode(400); + response.setBody(mapper.writeValueAsString(validationResponse)); + return response; + } + return new ObjectResult().create(body, this.URL, customHeaders); + } + public ResponseCulqi create(Map body, String rsaPublicKey, String rsaId) throws Exception { return new ObjectResult().create(body, this.URL, rsaPublicKey, rsaId); } + public ResponseCulqi create(Map body, String rsaPublicKey, String rsaId, Map customHeaders ) throws Exception { + return new ObjectResult().create(body, this.URL, rsaPublicKey, rsaId, customHeaders); + } + public ResponseCulqi get(String id) throws Exception { Map validationResponse = verifyClassValidationUpdate(id, this.URL); if (validationResponse != null) { @@ -64,8 +85,8 @@ public ResponseCulqi get(String id) throws Exception { } public ResponseCulqi update(Map body, String id) throws Exception { - Map validationResponse = verifyClassValidationUpdate(id, this.URL); - if (validationResponse != null) { + Map validationResponse = validatePayloadUpdate(id, this.URL, body); + if (validationResponse != null) { ResponseCulqi response = new ResponseCulqi(); response.setStatusCode(400); response.setBody(mapper.writeValueAsString(validationResponse)); @@ -73,10 +94,11 @@ public ResponseCulqi update(Map body, String id) throws Exceptio } return new ObjectResult().update(body, this.URL, id); } - - public ResponseCulqi update(Map body, String id, String rsaPublicKey, String rsaId) throws Exception { - Map validationResponse = verifyClassValidationUpdate(id, this.URL); - if (validationResponse != null) { + + public ResponseCulqi update(Map body, String id, String rsaPublicKey, String rsaId) + throws Exception { + Map validationResponse = validatePayloadUpdate(id, this.URL, body); + if (validationResponse != null) { ResponseCulqi response = new ResponseCulqi(); response.setStatusCode(400); response.setBody(mapper.writeValueAsString(validationResponse)); @@ -127,7 +149,24 @@ private static Map verifyClassValidationCreate(Map validatePayloadUpdate(String id, String url, Map body) + throws Exception { + try { + if (url.contains("plans")) { + Helper.validateStringStart(id, "pln"); + PlanValidation.update(body); + } + if (url.contains("subscriptions")) { + Helper.validateStringStart(id, "sxn"); + SubscriptionValidation.update(body); + } + } catch (CustomException e) { + return e.getErrorData(); + } + return null; + } + private static Map verifyClassValidationUpdate(String id, String url) throws Exception { try { if (url.contains("tokens")) { diff --git a/src/main/java/com/culqi/apioperation/service/Plan.java b/src/main/java/com/culqi/apioperation/service/Plan.java index 60d6ecb..7ec23ed 100644 --- a/src/main/java/com/culqi/apioperation/service/Plan.java +++ b/src/main/java/com/culqi/apioperation/service/Plan.java @@ -3,7 +3,7 @@ public class Plan extends Generic { - private static final String URL = "/plans/"; + private static final String URL = "/recurrent/plans/"; public Plan() { super(URL); diff --git a/src/main/java/com/culqi/apioperation/service/Subscription.java b/src/main/java/com/culqi/apioperation/service/Subscription.java index c8896d9..6914407 100644 --- a/src/main/java/com/culqi/apioperation/service/Subscription.java +++ b/src/main/java/com/culqi/apioperation/service/Subscription.java @@ -2,7 +2,7 @@ public class Subscription extends Generic { - private static final String URL = "/subscriptions/"; + private static final String URL = "/recurrent/subscriptions/"; public Subscription() { super(URL); diff --git a/src/main/java/com/culqi/util/validation/Helper.java b/src/main/java/com/culqi/util/validation/Helper.java index 4167093..9a216f8 100644 --- a/src/main/java/com/culqi/util/validation/Helper.java +++ b/src/main/java/com/culqi/util/validation/Helper.java @@ -1,10 +1,18 @@ package com.culqi.util.validation; + import java.util.regex.Pattern; + +import com.google.gson.Gson; + import java.util.regex.Matcher; import java.time.LocalDateTime; import java.time.Instant; import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; import java.util.List; +import java.util.Map; +import java.util.Set; public class Helper { public void validateAmount(Object amount) throws Exception { @@ -83,4 +91,246 @@ public static void validateAmountValue(Object amountObj) throws CustomException throw new CustomException("Invalid 'amount'. It should be an integer or a string representing an integer."); } } + + public static boolean validValue(Object value, Boolean isInteger) { + if (isInteger) { + if (!(value instanceof Integer)) { + return false; + } + } else { + if (!(value instanceof String)) { + return false; + } + } + return true; + } + + public static boolean validateRangeParameters(Object value, Integer minValue, Integer maxValue, Boolean isInteger) { + Integer num = isInteger ? Integer.parseInt(value.toString()) : value.toString().length(); + return num < minValue || num > maxValue; + } + + public static void validateCurrency(String currency, int amount) throws CustomException { + validateEnumCurrency(currency); + Integer MIN_AMOUNT_PEN = 3; + Integer MAX_AMOUNT_PEN = 5000; + Integer MIN_AMOUNT_USD = 1; + Integer MAX_AMOUNT_USD = 1500; + + int minAmountPublicApi = MIN_AMOUNT_PEN * 100; + int maxAmountPublicApi = MAX_AMOUNT_PEN * 100; + + if (currency.equals("USD")) { + minAmountPublicApi = MIN_AMOUNT_USD * 100; + maxAmountPublicApi = MAX_AMOUNT_USD * 100; + } + + boolean validAmount = amount >= minAmountPublicApi && amount <= maxAmountPublicApi; + + if (!validAmount) { + if (currency.equals("USD")) { + throw new CustomException("El campo 'amount' admite valores en el rango 100 a 150000."); + } + + throw new CustomException("El campo 'amount' admite valores en el rango 300 a 500000."); + } + } + + public static void validateInitialCycles(Map initialCycles) + throws CustomException { + boolean hasInitialCharge = (boolean) initialCycles.get("has_initial_charge"); + int payAmount = (int) initialCycles.get("amount"); + int count = (int) initialCycles.get("count"); + + if (!validValue(payAmount, true)) { + throw new CustomException( + "El campo 'initial_cycles.amount' es inválido o está vacío, debe tener un valor numérico."); + } + + if (hasInitialCharge) { + + if (count < 1 || count > 9999) { + throw new CustomException( + "El campo 'initial_cycles.count' solo admite valores numéricos en el rango 1 a 9999."); + } + + } else { + if (count < 0 || count > 9999) { + throw new CustomException( + "El campo 'initial_cycles.count' solo admite valores numéricos en el rango 0 a 9999."); + } + + } + } + + public static void validateEnumCurrency(String currency) throws CustomException { + List ENUM_CURRENCY = Arrays.asList("PEN", "USD"); + if (!ENUM_CURRENCY.contains(currency) || !validValue(currency, false)) { + throw new CustomException( + "El campo 'currency' es inválido o está vacío, el código de la moneda en tres letras (Formato ISO 4217). Culqi actualmente soporta las siguientes monedas: ['PEN','USD']."); + } + } + + public static String validateMetadataSchema(Map objMetadata) throws CustomException { + if (!(objMetadata instanceof Map) && !(objMetadata instanceof Object)) { + throw new CustomException("Enviaste el campo metadata con un formato incorrecto."); + } + + for (Map.Entry entry : objMetadata.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + int paramKey = key.length(); + int paramValue = value.toString().length(); + + if (paramKey < 1 || paramKey > 30 || paramValue < 1 || paramValue > 2000) { + throw new CustomException("El objeto 'metadata' es inválido, límite key (1 - 30), value (1 - 200)"); + } + } + + if (objMetadata instanceof Map && objMetadata.size() > 20) { + throw new CustomException("Enviaste más de 20 parámetros en el metadata. El límite es 20."); + } + + Map transformedMetadata = new HashMap<>(); + for (Map.Entry entry : objMetadata.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + transformedMetadata.put(key, value instanceof String ? (String) value : String.valueOf(value)); + } + + return new Gson().toJson(transformedMetadata); + } + + public static void validatePayloadCreatePlan(Map data) throws CustomException { + // Define la lista de parámetros esperados + List expectedParameters = Arrays.asList( + "interval_unit_time", + "interval_count", + "amount", + "name", + "description", + "short_name", + "currency", + "metadata", + "initial_cycles", + "image"); + + // Verifica si hay parámetros adicionales + Set extraParameters = new HashSet<>(data.keySet()); + extraParameters.removeAll(expectedParameters); + + if (!extraParameters.isEmpty()) { + throw new CustomException("Parámetros adicionales no permitidos: " + String.join(", ", extraParameters)); + } + } + + public static void validatePayloadCreateSubscription(Map data) throws CustomException { + // Define la lista de parámetros esperados + List expectedParameters = Arrays.asList( + "card_id", + "plan_id", + "metadata", + "tyc"); + + // Verifica si hay parámetros adicionales + Set extraParameters = new HashSet<>(data.keySet()); + extraParameters.removeAll(expectedParameters); + + if (!extraParameters.isEmpty()) { + throw new CustomException("Parámetros adicionales no permitidos: " + String.join(", ", extraParameters)); + } + } + + public static void validatePayloadUpdatePlan(Map data) throws CustomException { + // Define la lista de parámetros esperados + List expectedParameters = Arrays.asList( + "name", "description", "short_name", "status", "image", "metadata"); + + // Verifica si hay parámetros adicionales + Set extraParameters = new HashSet<>(data.keySet()); + extraParameters.removeAll(expectedParameters); + + if (!extraParameters.isEmpty()) { + throw new CustomException("Parámetros adicionales no permitidos: " + String.join(", ", extraParameters)); + } + } + + public static void validatePayloadUpdateSubscription(Map data) throws CustomException { + // Define la lista de parámetros esperados + List expectedParameters = Arrays.asList( + "card_id", "metadata"); + + // Verifica si hay parámetros adicionales + Set extraParameters = new HashSet<>(data.keySet()); + extraParameters.removeAll(expectedParameters); + + if (!extraParameters.isEmpty()) { + throw new CustomException("Parámetros adicionales no permitidos: " + String.join(", ", extraParameters)); + } + } + + public static void validatePayloadFilterPlan(Map data) throws CustomException { + // Define la lista de parámetros esperados + List expectedParameters = Arrays.asList( + "status", + "min_amount", + "max_amount", + "creation_date_to", + "creation_date_from", + "limit", + "after", + "before"); + + // Verifica si hay parámetros adicionales + Set extraParameters = new HashSet<>(data.keySet()); + extraParameters.removeAll(expectedParameters); + + if (!extraParameters.isEmpty()) { + throw new CustomException("Parámetros adicionales no permitidos: " + String.join(", ", extraParameters)); + } + } + + public static void validatePayloadFilterSubscription(Map data) throws CustomException { + // Define la lista de parámetros esperados + List expectedParameters = Arrays.asList( + "status", + "plan_id", + "creation_date_to", + "creation_date_from", + "limit", + "after", + "before"); + + // Verifica si hay parámetros adicionales + Set extraParameters = new HashSet<>(data.keySet()); + extraParameters.removeAll(expectedParameters); + + if (!extraParameters.isEmpty()) { + throw new CustomException("Parámetros adicionales no permitidos: " + String.join(", ", extraParameters)); + } + } + + public static void additionalValidation(Map data, List requiredFields, String message) throws CustomException { + for (String field : requiredFields) { + String errorMessage = "El campo '"; + + if (message != null && !message.isEmpty()) { + errorMessage += message + "."; + } + + errorMessage += field + "' es requerido"; + + if (!data.containsKey(field) || data.get(field) == null || data.get(field).toString().isEmpty() || data.get(field).toString().equals("undefined")) { + throw new CustomException(errorMessage); + } + } + } + + public static String getStringParameter(Map data, String key) { + return data.containsKey(key) ? String.valueOf(data.get(key)) : null; + } + + public static Integer getIntegerParameter(Map data, String key) { + return !validValue(data, true) && data.containsKey(key) ? (Integer) data.get(key) : null; + } } diff --git a/src/main/java/com/culqi/util/validation/PlanValidation.java b/src/main/java/com/culqi/util/validation/PlanValidation.java index 8c9e2e1..2710a2f 100644 --- a/src/main/java/com/culqi/util/validation/PlanValidation.java +++ b/src/main/java/com/culqi/util/validation/PlanValidation.java @@ -1,32 +1,231 @@ package com.culqi.util.validation; + import java.util.Arrays; +import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.regex.Pattern; public class PlanValidation { + + static String REGEX_IMAGE = "^(http://www\\.|https://www\\.|http://|https://)?[a-z0-9]+([-.]{1}[a-z0-9]+)*\\.[a-z]{2,5}(:[0-9]{1,5})?(/.*)?$"; + public static void create(Map data) throws Exception { - List allowedValues = Arrays.asList("dias", "semanas", "meses", "años"); - Helper.validateValue((String) data.get("interval"), allowedValues); - Object amountObj = data.get("amount"); - Helper.validateAmountValue(amountObj); - Helper.validateCurrencyCode((String) data.get("currency_code").toString()); + // Validate payload + List requiredFields = Arrays.asList( + "interval_unit_time", + "interval_count", + "amount", + "name", + "description", + "short_name", + "currency", + "initial_cycles"); + + Helper.additionalValidation(data, requiredFields, null); + Helper.validatePayloadCreatePlan(data); + + // Validate parameter: interval_unit_time + List allowedValues = Arrays.asList(1, 2, 3, 4, 5, 6); + if (!Helper.validValue(data.get("interval_unit_time"), true) || + !allowedValues.contains(data.get("interval_unit_time"))) { + throw new CustomException( + "El campo 'interval_unit_time' tiene un valor inválido o está vacío. Estos son los únicos valores permitidos: [ 1, 2, 3, 4, 5, 6]."); + } + + if (Helper.validateRangeParameters(data.get("interval_count"), 0, 9999, true) || + !Helper.validValue(data.get("interval_unit_time"), true)) { + throw new CustomException( + "El campo 'interval_count' solo admite valores numéricos en el rango 0 a 9999."); + } + + if (!Helper.validValue(data.get("amount"), true)) { + throw new CustomException( + "El campo 'amount' es inválido o está vacío, debe tener un valor numérico entero."); + } + + if (!Helper.validValue(data.get("name"), false) || + Helper.validateRangeParameters(data.get("name"), 5, 50, false)) { + throw new CustomException( + "El campo 'name' es inválido o está vacío. El valor debe tener un rango de 5 a 50 caracteres."); + } + + if (!Helper.validValue(data.get("description"), false) || + Helper.validateRangeParameters(data.get("description"), 5, 250, false)) { + throw new CustomException( + "El campo 'description' es inválido o está vacío. El valor debe tener un rango de 5 a 250 caracteres."); + } + + if (!Helper.validValue(data.get("short_name"), false) || + Helper.validateRangeParameters(data.get("short_name"), 5, 50, false)) { + throw new CustomException( + "El campo 'short_name' es inválido o está vacío. El valor debe tener un rango de 5 a 50 caracteres."); + } + + if (data.get("initial_cycles") == null) { + throw new CustomException( + "El campo 'initial_cycles' es requerido."); + } + + Helper.validateEnumCurrency(data.get("currency").toString()); + + Map initialCycles = (Map) data.get("initial_cycles"); + if (!Helper.validValue(initialCycles.get("count"), true)) { + throw new CustomException( + "El campo 'initial_cycles.count' es inválido o está vacío, debe tener un valor numérico."); + } + if (!initialCycles.containsKey("amount") || initialCycles.get("amount") == null || !(initialCycles.get("amount") instanceof Integer)) { + throw new CustomException( + "El campo 'initial_cycles.amount' es inválido o está vacío, debe tener un valor numérico entero."); + } + + if (!Helper.validValue(initialCycles.get("amount"), true)) { + throw new CustomException( + "El campo 'initial_cycles.amount' es inválido o está vacío, debe tener un valor numérico entero."); + } + + if (!Helper.validValue(initialCycles.get("interval_unit_time"), true) || + !allowedValues.contains(initialCycles.get("interval_unit_time"))) { + throw new CustomException( + "El campo 'initial_cycles.interval_unit_time' tiene un valor inválido o está vacío. Estos son los únicos valores permitidos: [ 1, 2, 3, 4, 5, 6]."); + } + + if (!(initialCycles.get("has_initial_charge") instanceof Boolean)) { + throw new CustomException( + "El campo 'initial_cycles.has_initial_charge' es inválido o está vacío. El valor debe ser un booleano (true o false)."); + } + + Helper.validateInitialCycles(initialCycles); + + if (data.containsKey("metadata")) { + Helper.validateMetadataSchema((Map) data.get("metadata")); + } + + if (data.containsKey("image")) { + if (Helper.validateRangeParameters(data.get("image"), 5, 250, false) || + !Pattern.matches(REGEX_IMAGE, data.get("image").toString())) { + throw new CustomException( + "El campo 'image' es inválido o está vacío. El valor debe ser una cadena y debe ser una URL válida de 5 a 250 caracteres."); + } + } } public static void list(Map data) throws Exception { - if (data.containsKey("amount")) { - Object amountObj = data.get("amount"); - Helper.validateAmountValue(amountObj); + + Helper.validatePayloadFilterPlan(data); + + List PLAN_STATUS = Arrays.asList(1, 2); + if (data.containsKey("status")) { + if (!PLAN_STATUS.contains(data.get("status"))) { + throw new CustomException( + "El filtro 'status' tiene un valor inválido o está vacío. Estos son los únicos valores permitidos: 1, 2."); + } } + if (data.containsKey("min_amount")) { - Object amountObj = data.get("min_amount"); - Helper.validateAmountValue(amountObj); + if (!Helper.validValue(data.get("min_amount"), true)) { + throw new CustomException( + "El filtro 'min_amount' es invalido, debe tener un valor numérico entero."); + } } + if (data.containsKey("max_amount")) { - Object amountObj = data.get("max_amount"); - Helper.validateAmountValue(amountObj); + if (!Helper.validValue(data.get("max_amount"), true)) { + throw new CustomException( + "El filtro 'max_amount' es invalido, debe tener un valor numérico entero."); + } + } + + if (data.containsKey("limit")) { + if (!Helper.validValue(data.get("limit"), true) || + Helper.validateRangeParameters(data.get("limit"), 1, 100, true)) { + throw new CustomException( + "El filtro 'limit' admite valores en el rango 1 a 100."); + } + } + + Integer GENERATED_ID = 25; + if (data.containsKey("before")) { + if (!Helper.validValue(data.get("before"), false) || + data.get("before").toString().length() != GENERATED_ID) { + throw new CustomException( + "El campo 'before' es inválido. La longitud debe ser de 25 caracteres."); + } + } + + if (data.containsKey("after")) { + if (!Helper.validValue(data.get("after"), false) || + data.get("after").toString().length() != GENERATED_ID) { + throw new CustomException( + "El campo 'after' es inválido. La longitud debe ser de 25 caracteres."); + } + } + + if (data.containsKey("creation_date_from")) { + Object creationDateFrom = data.get("creation_date_from"); + + if (String.valueOf(creationDateFrom).length() != 10 && String.valueOf(creationDateFrom).length() != 13) { + throw new CustomException( + "El campo 'creation_date_from' debe tener una longitud diferente de 10 o 13 caracteres."); + } + } + + if (data.containsKey("creation_date_to")) { + Object creationDateTo = data.get("creation_date_to"); + + if (String.valueOf(creationDateTo).length() != 10 && String.valueOf(creationDateTo).length() != 13) { + throw new CustomException( + "El campo 'creation_date_to' debe tener una longitud diferente de 10 o 13 caracteres."); + } + } + } + + public static void update(Map data) throws Exception { + Helper.validatePayloadUpdatePlan(data); + + if (data.containsKey("name")) { + if (!Helper.validValue(data.get("name"), false) || + Helper.validateRangeParameters(data.get("name"), 5, 50, false)) { + throw new CustomException( + "El campo 'name' es inválido o está vacío. El valor debe tener un rango de 5 a 50 caracteres."); + } + } + + if (data.containsKey("description")) { + if (!Helper.validValue(data.get("description"), false) || + Helper.validateRangeParameters(data.get("description"), 5, 250, false)) { + throw new CustomException( + "El campo 'description' es inválido o está vacío. El valor debe tener un rango de 5 a 250 caracteres."); + } } - if (data.containsKey("creation_date_from") && data.containsKey("creation_date_to")) { - Helper.validateDateFilter((String) data.get("creation_date_from"), (String) data.get("creation_date_to")); + + if (data.containsKey("shortName")) { + if (!Helper.validValue(data.get("short_name"), false) || + Helper.validateRangeParameters(data.get("short_name"), 5, 250, false)) { + throw new CustomException( + "El campo 'short_name' es inválido o está vacío. El valor debe tener un rango de 5 a 50 caracteres."); + } + } + + List PLAN_STATUS = Arrays.asList(1, 2); + if (data.containsKey("status")) { + if (!PLAN_STATUS.contains(data.get("status"))) { + throw new CustomException( + "El filtro 'status' tiene un valor inválido o está vacío. Estos son los únicos valores permitidos: 1, 2."); + } + } + + if (data.containsKey("image")) { + if (Helper.validateRangeParameters(data.get("image"), 5, 250, false) || + !Pattern.matches(REGEX_IMAGE, data.get("image").toString())) { + throw new CustomException( + "El campo 'image' es inválido o está vacío. El valor debe ser una cadena y debe ser una URL válida."); + } + } + + if (data.containsKey("metadata")) { + Helper.validateMetadataSchema((Map) data.get("metadata")); } } + } diff --git a/src/main/java/com/culqi/util/validation/SubscriptionValidation.java b/src/main/java/com/culqi/util/validation/SubscriptionValidation.java index 6986cf7..4279495 100644 --- a/src/main/java/com/culqi/util/validation/SubscriptionValidation.java +++ b/src/main/java/com/culqi/util/validation/SubscriptionValidation.java @@ -1,19 +1,137 @@ package com.culqi.util.validation; + +import java.util.Arrays; +import java.util.List; import java.util.Map; public class SubscriptionValidation { public static void create(Map data) throws Exception { + + List requiredFields = Arrays.asList( + "card_id", + "plan_id", + "tyc" + ); + + Helper.additionalValidation(data, requiredFields, null); + Helper.validatePayloadCreateSubscription(data); + + Integer GENERATED_ID = 25; + // Validate card_id format + if (!Helper.validValue(data.get("card_id"), false) || + data.get("card_id").toString().length() != GENERATED_ID) { + throw new CustomException( + "El campo 'card_id' es inválido. La longitud debe ser de 25 caracteres."); + } Helper.validateStringStart((String) data.get("card_id"), "crd"); + + // Validate plan_id format + if (!Helper.validValue(data.get("plan_id"), false) || + data.get("plan_id").toString().length() != GENERATED_ID) { + throw new CustomException( + "El campo 'plan_id' es inválido. La longitud debe ser de 25 caracteres."); + } Helper.validateStringStart((String) data.get("plan_id"), "pln"); + + + // Validate parameter: metadata + if (data.containsKey("metadata")) { + Helper.validateMetadataSchema((Map) data.get("metadata")); + } + + // Validate parameter: tyc + if (!data.containsKey("tyc") || !(Boolean.FALSE.equals(data.get("tyc")) + || Boolean.TRUE.equals(data.get("tyc")))) { + throw new CustomException( + "El campo 'tyc' es inválido o está vacío. El valor debe ser un booleano."); + } + } public static void list(Map data) throws Exception { + + Helper.validatePayloadFilterSubscription(data); + List SUBSCRIPTION_STATUS = Arrays.asList(1, 2, 3, 4, 5, 6, 8); + // Validar parámetro: status + if (data.containsKey("status")) { + if (!SUBSCRIPTION_STATUS.contains(data.get("status"))) { + throw new CustomException( + "El filtro 'status' tiene un valor inválido o está vacío. Estos son los únicos valores permitidos: [1, 2, 3, 4, 5, 6, 8]."); + } + } + + if (data.containsKey("limit")) { + if (!Helper.validValue(data.get("limit"), true) || + Helper.validateRangeParameters(data.get("limit"), 1, 100, true)) { + throw new CustomException( + "El filtro 'limit' admite valores en el rango 1 a 100."); + } + } + + Integer GENERATED_ID = 25; if (data.containsKey("plan_id")) { + if (!Helper.validValue(data.get("plan_id"), false) || + data.get("plan_id").toString().length() != GENERATED_ID) { + throw new CustomException( + "El campo 'plan_id' es inválido. La longitud debe ser de 25 caracteres."); + } Helper.validateStringStart((String) data.get("plan_id"), "pln"); } + if (data.containsKey("before")) { + if (!Helper.validValue(data.get("before"), false) || + data.get("before").toString().length() != GENERATED_ID) { + throw new CustomException( + "El campo 'before' es inválido. La longitud debe ser de 25 caracteres."); + } + } + + if (data.containsKey("after")) { + if (!Helper.validValue(data.get("after"), false) || + data.get("after").toString().length() != GENERATED_ID) { + throw new CustomException( + "El campo 'after' es inválido. La longitud debe ser de 25 caracteres."); + } + } + + if (data.containsKey("creation_date_from")) { + Object creationDateFrom = data.get("creation_date_from"); + + if (String.valueOf(creationDateFrom).length() != 10 && String.valueOf(creationDateFrom).length() != 13) { + throw new CustomException( + "El campo 'creation_date_from' debe tener una longitud diferente de 10 o 13 caracteres."); + } + } + + if (data.containsKey("creation_date_to")) { + Object creationDateTo = data.get("creation_date_to"); + + if (String.valueOf(creationDateTo).length() != 10 && String.valueOf(creationDateTo).length() != 13) { + throw new CustomException( + "El campo 'creation_date_to' debe tener una longitud diferente de 10 o 13 caracteres."); + } + } + + } + + public static void update(Map data) throws Exception { + List requiredFields = Arrays.asList( + "card_id" + ); + + Helper.additionalValidation(data, requiredFields, null); + Helper.validatePayloadUpdateSubscription(data); + Integer GENERATED_ID = 25; + // Validate card_id format + if (!Helper.validValue(data.get("card_id"), false) || + data.get("card_id").toString().length() != GENERATED_ID || !data.containsKey("card_id")) { + throw new CustomException( + "El campo 'card_id' es inválido. La longitud debe ser de 25 caracteres."); + } - if (data.containsKey("creation_date_from") && data.containsKey("creation_date_to")) { - Helper.validateDateFilter((String) data.get("creation_date_from"), (String) data.get("creation_date_to")); + Helper.validateStringStart(data.get("card_id").toString(), "crd"); + // Validate parameter: metadata + if (data.containsKey("metadata")) { + Helper.validateMetadataSchema((Map) data.get("metadata")); } } } diff --git a/src/test/java/CulqiCRUD.java b/src/test/java/CulqiCRUD.java index 4583305..c82aa8e 100644 --- a/src/test/java/CulqiCRUD.java +++ b/src/test/java/CulqiCRUD.java @@ -72,12 +72,32 @@ protected ResponseCulqi createCharge() throws Exception { String source_id = res.get("id").toString();System.out.println("source_id "+source_id); return init().charge.create(jsondata.jsonCharge(source_id)); } + + protected ResponseCulqi createRecurrentCharge() throws Exception { + Map res = mapper.readValue(createToken().getBody(), new TypeReference>(){}); + String source_id = res.get("id").toString(); + + Map customHeaders = new HashMap(); + customHeaders.put("X-Charge-Channel", "recurrent"); + + return init().charge.create(jsondata.jsonCharge(source_id), customHeaders); + } protected ResponseCulqi createChargeEncrypt() throws Exception { Map res = mapper.readValue(createToken().getBody(), new TypeReference>(){}); String source_id = res.get("id").toString(); return init().charge.create(jsondata.jsonCharge(source_id), rsaPublicKey, rsaId); } + + protected ResponseCulqi createRecurrentChargeEncrypt() throws Exception { + Map res = mapper.readValue(createToken().getBody(), new TypeReference>(){}); + String source_id = res.get("id").toString(); + + Map customHeaders = new HashMap(); + customHeaders.put("X-Charge-Channel", "recurrent"); + + return init().charge.create(jsondata.jsonCharge(source_id), rsaPublicKey, rsaId, customHeaders); + } protected ResponseCulqi updateCharge() throws Exception { Map res = mapper.readValue(createCharge().getBody(), new TypeReference>(){}); @@ -126,12 +146,12 @@ protected ResponseCulqi createSubscription() throws Exception { String plan_id = res2.get("id").toString(); return init().subscription.create(jsondata.jsonSubscription(card_id, plan_id)); } - + protected ResponseCulqi updateSubscription() throws Exception { - Map res = mapper.readValue(createSubscription().getBody(), new TypeReference>(){}); + Map res = mapper.readValue(createSubscription().getBody(), new TypeReference>(){}); String id = res.get("id").toString(); - return init().subscription.update(jsondata.jsonUpdateCard(), id); - } + return init().subscription.update(jsondata.jsonUpdateSubscription(), id); + } protected ResponseCulqi createRefund() throws Exception { Map res = mapper.readValue(createCharge().getBody(), new TypeReference>(){}); @@ -160,7 +180,7 @@ protected ResponseCulqi charges() throws Exception { } protected ResponseCulqi plans() throws Exception { - return init().plan.list(); + return init().plan.list(jsondata.jsonPlanFilter()); } protected ResponseCulqi customers() throws Exception { diff --git a/src/test/java/CulqiCreateTest.java b/src/test/java/CulqiCreateTest.java index d2c672e..4dac7ce 100644 --- a/src/test/java/CulqiCreateTest.java +++ b/src/test/java/CulqiCreateTest.java @@ -43,6 +43,7 @@ public void test03_createTokenYape() throws Exception { public void test04_createCharge() throws Exception { ResponseCulqi response = culqiCRUD.createCharge(); Map res = mapper.readValue(response.getBody(), new TypeReference>(){}); + System.err.println("Response: "+response); if (response.getStatusCode()==200) { System.err.println(response); assertEquals("REVIEW",res.get("action_code").toString()); @@ -51,6 +52,20 @@ public void test04_createCharge() throws Exception { assertEquals("charge",res.get("object").toString()); } } + + @Test + public void test04_createRecurrentCharge() throws Exception { + ResponseCulqi response = culqiCRUD.createRecurrentCharge(); + Map res = mapper.readValue(response.getBody(), new TypeReference>(){}); + System.err.println("Response: "+response); + if (response.getStatusCode()==200) { + System.err.println(response); + assertEquals("REVIEW",res.get("action_code").toString()); + }else if (response.getStatusCode()==201) { + System.err.println(res); + assertEquals("charge",res.get("object").toString()); + } + } @Test public void test04_createChargeEncrypt() throws Exception { @@ -63,11 +78,23 @@ public void test04_createChargeEncrypt() throws Exception { } } + @Test + public void test04_createRecurrentChargeEncrypt() throws Exception { + ResponseCulqi response = culqiCRUD.createRecurrentChargeEncrypt(); + Map res = mapper.readValue(response.getBody(), new TypeReference>(){}); + if (response.getStatusCode()==200) { + assertEquals("REVIEW",res.get("action_code").toString()); + }else if (response.getStatusCode()==201) { + assertEquals("charge",res.get("object").toString()); + } + } + @Test public void test05_createPlan() throws Exception { - Map res = mapper.readValue(culqiCRUD.createPlan().getBody(), new TypeReference>(){}); - assertEquals("plan",res.get("object").toString()); + Map res = mapper.readValue(culqiCRUD.createPlan().getBody(), new TypeReference>(){}); + Object id = res.get("id"); + assertTrue(id instanceof String); } @Test @@ -90,8 +117,9 @@ public void test07_createCard() throws Exception { @Test public void test08_createSubscription() throws Exception { - Map res = mapper.readValue(culqiCRUD.createSubscription().getBody(), new TypeReference>(){}); - assertEquals("subscription",res.get("object").toString()); + Map res = mapper.readValue(culqiCRUD.createSubscription().getBody(), new TypeReference>(){}); + Object id = res.get("id"); + assertTrue(id instanceof String); } @Test diff --git a/src/test/java/CulqiGetTest.java b/src/test/java/CulqiGetTest.java index 62a7ef9..ce9e280 100644 --- a/src/test/java/CulqiGetTest.java +++ b/src/test/java/CulqiGetTest.java @@ -58,14 +58,16 @@ public void test05_findCard() throws Exception { public void test06_findPlan() throws Exception { Map res = mapper.readValue(culqiCRUD.createPlan().getBody(), new TypeReference>(){}); Map planFound = mapper.readValue(culqiCRUD.init().plan.get(res.get("id").toString()).getBody(), new TypeReference>(){}); - assertEquals("plan", planFound.get("object").toString()); + Object id = planFound.get("id"); + assertTrue(id instanceof String); } @Test public void test07_findSubscription() throws Exception { Map res = mapper.readValue(culqiCRUD.createSubscription().getBody(), new TypeReference>(){}); Map subscriptionFound = mapper.readValue(culqiCRUD.init().subscription.get(res.get("id").toString()).getBody(), new TypeReference>(){}); - assertEquals("subscription", subscriptionFound.get("object").toString()); + Object id = subscriptionFound.get("id"); + assertTrue(id instanceof String); } @Test diff --git a/src/test/java/CulqiPatchTest.java b/src/test/java/CulqiPatchTest.java index 831f504..0c36838 100644 --- a/src/test/java/CulqiPatchTest.java +++ b/src/test/java/CulqiPatchTest.java @@ -51,14 +51,16 @@ public void test05_updateCard() throws Exception { @Test public void test06_updatePlan() throws Exception { - Map res = mapper.readValue(culqiCRUD.updatePlan().getBody(), new TypeReference>(){}); - assertEquals("plan", res.get("object").toString()); + Map res = mapper.readValue(culqiCRUD.updatePlan().getBody(), new TypeReference>(){}); + Object id = res.get("id"); + assertTrue(id instanceof String); } @Test public void test07_updateSubscription() throws Exception { - Map res = mapper.readValue(culqiCRUD.updateSubscription().getBody(), new TypeReference>(){}); - assertEquals("subscription", res.get("object").toString()); + Map res = mapper.readValue(culqiCRUD.updateSubscription().getBody(), new TypeReference>(){}); + Object id = res.get("id"); + assertTrue(id instanceof String); } @Test diff --git a/src/test/java/JsonData.java b/src/test/java/JsonData.java index 0c5d417..6fb68d2 100644 --- a/src/test/java/JsonData.java +++ b/src/test/java/JsonData.java @@ -113,28 +113,55 @@ protected Map jsonListCharges() throws Exception { return charge; } + protected Map jsonPlanFilter() throws Exception { + Map plan = new HashMap(); + plan.put("status", 1); + plan.put("limit", 1); + plan.put("before","pln_live_qnJOtJiuGT88dAa5"); + plan.put("after", "pln_live_qnJOtJiuGT88dAa5"); + plan.put("min_amount", 300); + plan.put("max_amount", 500000); + //plan.put("creation_date_from", "1712673354"); + //plan.put("creation_date_to", "1712673354"); + return plan; + } + protected Map jsonPlan() throws Exception { Map plan = new HashMap(); + Map initial_cycles = new HashMap(); Map metadata = new HashMap(); metadata.put("order_id", "124"); - plan.put("amount", 1000); - plan.put("currency_code", CurrencyCode.PEN); - plan.put("interval", "dias"); - plan.put("interval_count", 30); - plan.put("limit", 4); - plan.put("metadata", metadata); + initial_cycles.put("count", 1); + initial_cycles.put("has_initial_charge", true); + initial_cycles.put("amount", 301); + initial_cycles.put("interval_unit_time", 1); plan.put("name", "plan-" + new Util().ramdonString()); - plan.put("trial_days", 15); + plan.put("short_name", "plan-" + new Util().ramdonString()); + plan.put("description", "description - "); + plan.put("amount", 300); + plan.put("currency", CurrencyCode.PEN); + plan.put("interval_unit_time", 1); + plan.put("interval_count", 0); + plan.put("image", + "https://img.freepik.com/foto-gratis/resumen-bombilla-creativa-sobre-fondo-azul-brillante-ia-generativa_188544-8090.jpg"); + plan.put("metadata", metadata); + plan.put("initial_cycles", initial_cycles); return plan; } - + protected Map jsonUpdatePlan() throws Exception { - Map plan = new HashMap(); - Map metadata = new HashMap(); - metadata.put("oder_id", "899"); - plan.put("metadata", metadata); - return plan; - } + Map plan = new HashMap(); + Map metadata = new HashMap(); + //metadata.put("oder_id", "899"); + //plan.put("name", "plan-" + new Util().ramdonString()); + //plan.put("short_name", "plan-" + new Util().ramdonString()); + plan.put("description", "description - "); + plan.put("status", 1); + //plan.put("image", + // "https://img.freepik.com/foto-gratis/resumen-bombilla-creativa-sobre-fondo-azul-brillante-ia-generativa_188544-8090.jpg"); + plan.put("metadata", metadata); + return plan; + } protected Map jsonCustomer() throws Exception { Map customer = new HashMap(); @@ -205,25 +232,35 @@ protected Map jsonListRefunds() throws Exception { return refund; } - protected Map jsonSubscription(String cardId, String planId) throws Exception { - Map subscription = new HashMap(); - subscription.put("card_id",cardId); - subscription.put("plan_id",planId); - return subscription; - } - - protected Map jsonUpdateSubscription() throws Exception { - Map obj = new HashMap(); - Map metadata = new HashMap(); - metadata.put("dni", "89941525"); - obj.put("metadata", metadata); - return obj; - } - - protected Map jsonListSubscriptions() throws Exception { - Map subscription = new HashMap(); - subscription.put("min_amount", 500); - subscription.put("max_amount", 900); - return subscription; - } + protected Map jsonSubscription(String cardId, String planId) throws Exception { + Map subscription = new HashMap(); + Map metadata = new HashMap(); + metadata.put("order_id", "124"); + subscription.put("card_id", cardId); + subscription.put("plan_id", planId); + subscription.put("tyc", true); + subscription.put("metadata", metadata); + return subscription; + } + + protected Map jsonUpdateSubscription() throws Exception { + Map subscription = new HashMap(); + Map metadata = new HashMap(); + //metadata.put("card_id", "89941525"); + subscription.put("card_id", "crd_live_****************"); + subscription.put("metadata", metadata); + return subscription; + } + + protected Map jsonListSubscriptions() throws Exception { + Map subscription = new HashMap(); + //subscription.put("plan_id", "pln_live_****************"); + //subscription.put("status", 1); + subscription.put("limit", 100); + //subscription.put("before", "sxn_live_****************"); + //subscription.put("after", "sxn_live_****************"); + //subscription.put("creation_date_from", "1712673354"); + //subscription.put("creation_date_to", "1712673354"); + return subscription; + } }