[ADD] BBVA CAMBIOS

parent 04a2dac9
...@@ -4,38 +4,26 @@ import org.json.JSONObject; ...@@ -4,38 +4,26 @@ import org.json.JSONObject;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import web.multitask.trismegistoservices.services.BBVA.bbvaService; import web.multitask.trismegistoservices.services.BBVA.bbvaService;
import web.multitask.trismegistoservices.singleton.bbvaSingleton;
@RestController @RestController
@CrossOrigin(origins = "*") @CrossOrigin(origins = "*")
@RequestMapping("bbva") @RequestMapping("bbva")
public class bbvaRest { public class bbvaRest {
private final bbvaSingleton singleton; @PostMapping("/private/generate/qr")
public ResponseEntity<?> generateQR(@RequestBody String json) {
public bbvaRest(bbvaSingleton singleton) { bbvaService service = new bbvaService();
this.singleton = singleton; JSONObject jsonRequest = new JSONObject(json);
JSONObject jsonResponse = service.generalService(jsonRequest);
return ResponseEntity.ok(jsonResponse.toMap());
} }
@PostMapping("/private/prepareRequest") @GetMapping("/private/status/qr/{id}")
public ResponseEntity<?> getHeader(@RequestBody String json) { public ResponseEntity<?> getStatus( @PathVariable String id) {
bbvaService service = new bbvaService(); bbvaService service = new bbvaService();
JSONObject response = service.getToken(json); JSONObject jsonResponse = service.getStatus(id);
String token = response.optString("access_token"); return ResponseEntity.ok(jsonResponse.toMap());
if(token.isEmpty()){
return ResponseEntity.internalServerError().body(response.put("status",false).put("token","").toMap());
}else{
singleton.setToken(token);
String digest = service.bodyIntoBase64AfterSHA512(json);
singleton.setDigest(digest);
String txt = service.txtToSign(json ,digest);
String signature = service.createSignature(txt);
singleton.setSignature(signature);
System.out.println("token = "+singleton.getToken());
System.out.println("digest = "+singleton.getDigest());
System.out.println("signature = "+singleton.getSignature());
return ResponseEntity.ok(service.peticionHTTP(singleton.getToken(),singleton.getDigest(),singleton.getSignature(),json).toMap());
}
} }
} }
package web.multitask.trismegistoservices.services.BBVA;
import okhttp3.*;
import okio.Buffer;
import org.json.JSONObject;
import web.multitask.trismegistoservices.utils.CommonUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.zip.GZIPInputStream;
public class bbvaUtils {
String host = "apis.pe.bbvaapimarket.com";
String client_secret = "513375e5181e462fb3ec7a00dfc26dc7";
String client_id = "174895823298";
String grant_type = "client_credentials";
String globalDate = CommonUtils.getCurrentDateRFC1123();
public String getToken() {
final MediaType FORM_URLENCODED = MediaType.parse("application/x-www-form-urlencoded");
try {
JSONObject obj = new JSONObject();
obj.put("client_secret", client_secret);
obj.put("client_id", client_id);
obj.put("grant_type", grant_type);
String formBody = CommonUtils.jsonToUrlEncoded(obj);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://" + host + "/auth/oauth/v2/token")
.post(RequestBody.create(formBody, FORM_URLENCODED))
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
System.err.println("HTTP Error: " + response.code() + " - " + response.message());
return null;
}
String responseBody = response.body() != null ? response.body().string() : "";
JSONObject jsonObject = new JSONObject(responseBody);
return jsonObject.optString("access_token", null);
}
} catch (Exception e) {
System.err.println("Error getting token: " + e.getMessage());
return null;
}
}
public String hashDigest(String json) {
try {
JSONObject jsonObject = new JSONObject(json);
String body = jsonObject.optString("body", "");
byte[] bodyBytes = body.getBytes(StandardCharsets.UTF_8);
MessageDigest digest = MessageDigest.getInstance("SHA-512");
byte[] hashedBytes = digest.digest(bodyBytes);
return Base64.getEncoder().encodeToString(hashedBytes);
} catch (Exception e) {
System.err.println("Error generating digest: " + e.getMessage());
return null;
}
}
public String txtToSign(JSONObject json, String digest) {
try{
String endpoint = json.getString("endpoint");
String method = json.getString("method");
return "(request-target):" + method.toLowerCase() + " " + endpoint + "\n"
+ "host:" + host + "\n"
+ "date:" + globalDate + "\n"
+ "digest:SHA-512=" + digest;
}catch (Exception e){
System.err.println("Error generating txtToSign: " + e.getMessage());
return null;
}
}
public String createSignature(String txt) {
PrivateKey privateKey = loadPrivateKey("/tokens/key.p8");
return signContent(txt, privateKey);
}
public PrivateKey loadPrivateKey(String path) {
try (InputStream in = bbvaService.class.getResourceAsStream(path)) {
assert in != null;
String keyString = CommonUtils.readInputStream(in);
return loadPrivateKeyFromString(keyString);
} catch (Exception e) {
System.err.println("Error loading private key: " + e.getMessage());
return null;
}
}
private static PrivateKey loadPrivateKeyFromString(String keyString) throws Exception {
keyString = keyString.replace("-----BEGIN RSA PRIVATE KEY-----", "")
.replace("-----END RSA PRIVATE KEY-----", "")
.trim();
byte[] keyBytes = Base64.getMimeDecoder().decode(keyString);
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePrivate(spec);
}
public String signContent(String content, PrivateKey privateKey) {
try {
Signature signature = Signature.getInstance("SHA512withRSA");
signature.initSign(privateKey);
signature.update(content.getBytes());
byte[] signedBytes = signature.sign();
return Base64.getEncoder().encodeToString(signedBytes);
} catch (Exception e) {
System.err.println("Error signing content: " + e.getMessage());
return null;
}
}
public JSONObject peticionHTTP(String token, String digest, String signature, JSONObject json) {
try {
String endpoint = json.getString("endpoint");
String extra = json.optString("extra", "");
String method = json.optString("method", "get").toLowerCase();
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
RequestBody requestBody = null;
if ("post".equals(method)) {
JSONObject body = json.optJSONObject("body", new JSONObject());
requestBody = RequestBody.create(body.toString(), mediaType);
}
Request.Builder builder = new Request.Builder()
.url("https://" + host + endpoint + extra)
.addHeader("Content-Type", "application/json")
.addHeader("Accept-Encoding", "gzip")
.addHeader("Authorization", "Bearer " + token)
.addHeader("Digest", "SHA-512=" + digest)
.addHeader("Signature", "algorithm=\"rsa-sha512\",headers=\"(request-target) host date digest\",signature=\"" + signature + "\"")
.addHeader("Host", host)
.addHeader("Date", globalDate);
Request request = "post".equals(method) ? builder.post(requestBody).build() : builder.get().build();
StringBuilder requestInfo = new StringBuilder();
requestInfo.append("URL: ").append(request.url()).append("\n");
requestInfo.append("Method: ").append(request.method()).append("\n");
requestInfo.append("Headers:\n");
for (String name : request.headers().names()) {
requestInfo.append(" ").append(name).append(": ").append(request.header(name)).append("\n");
}
if (request.body() != null) {
try {
Buffer buffer = new Buffer();
request.body().writeTo(buffer);
String bodyString = buffer.readUtf8();
requestInfo.append("Body:\n").append(bodyString).append("\n");
} catch (IOException e) {
requestInfo.append("Body: (error reading body)\n");
}
}
System.out.println(requestInfo);
try (Response response = client.newCall(request).execute()) {
System.out.println("x-request-id = " + response.header("x-request-id"));
String bodyResult;
if (response.code() == 204) {
bodyResult = "{}";
} else if (response.body() != null) {
String encoding = response.header("Content-Encoding", "");
bodyResult = "gzip".equalsIgnoreCase(encoding)
? decompressGzip(response.body().byteStream())
: response.body().string();
} else {
bodyResult = "{}";
}
System.out.println(bodyResult);
return new JSONObject(bodyResult);
}
} catch (Exception e) {
System.out.println(e.getMessage());
return new JSONObject().put("status", false).put("message", e.getMessage());
}
}
private String decompressGzip(InputStream compressed) throws IOException {
try (GZIPInputStream gis = new GZIPInputStream(compressed);
BufferedReader reader = new BufferedReader(new InputStreamReader(gis, StandardCharsets.UTF_8))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} catch (Exception e) {
System.out.println(e.getMessage());
return "";
}
}
public String numberToMonth(int number) {
String[] months = {"ENERO", "FEBRERO", "MARZO", "ABRIL", "MAYO", "JUNIO", "JULIO", "AGOSTO", "SETIEMBRE", "OCTUBRE", "NOVIEMBRE", "DICIEMBRE"};
return months[number - 1];
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment