Worker (CloudFlare): Consulta de Documentos Dinámicos
Secretos Worker (Variables de Entorno)
API_KEY
SECRET_KEY
API_ENDPOINT
export default {
async fetch(request, env, ctx) {
return this.handleRequest(request,env);
},
async calculateHmac(secretKey, params) {
const encoder = new TextEncoder();
const dataString = Object.entries(params).sort().map(([key, value]) => `${key}=${value}`).join('');
const secretKeyBytes = encoder.encode(secretKey);
const dataBytes = encoder.encode(dataString);
const hmac = await crypto.subtle.importKey("raw", secretKeyBytes, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
const signature = await crypto.subtle.sign("HMAC", hmac, dataBytes);
return Array.from(new Uint8Array(signature)).map(b => b.toString(16).padStart(2, '0')).join('');
},
async sendSignedRequest(endpoint, path, postParams, apiKey, secretKey) {
postParams['dinaup_apikey'] = apiKey;
postParams['dinaup_usuarioip'] = "local";
postParams['dinaup_usuarionavegador'] = "cloudflare_worker";
postParams['signature'] = await this.calculateHmac(secretKey, postParams);
const formData = new URLSearchParams();
for (const [key, value] of Object.entries(postParams)) {
formData.append(key, value);
}
const response = await fetch(`${endpoint}/${path}`, {
method: "POST",
body: formData,
headers: { "Content-Type": "application/x-www-form-urlencoded" }
});
return response.text();
},
async handleRequest(request,env) {
const url = new URL(request.url);
const docdinamicoId = url.searchParams.get("docId");
const params = Object.fromEntries(url.searchParams.entries());
// Asegúrate de definir tus claves reales aquí
const apiKey = env.API_KEY;
const secretKey = env.SECRET_KEY;
// Asegúrate de ajustar la URL del endpoint si es necesario
const endpoint = env.API_ENDPOINT;
// Envía la solicitud firmada a la API de Dinaup
const responseJson = await this.sendSignedRequest(endpoint, "docdinamico", { ...params, 'dinaup_dd_id': docdinamicoId }, apiKey, secretKey);
// Aquí puedes decidir cómo manejar y responder con el JSON recibido de la API
return new Response(responseJson, { status: 200 });
}
}
Last modified: 28 November 2024