Headers de autenticación
Con el propósito de reforzar la seguridad y garantizar la integridad del contenido enviado desde el comercio hacia los servicios de nuestra pasarela de pagos, es esencial incorporar ciertos encabezados (header) en cada solicitud al servidor. Para ello, se utiliza el algoritmo SHA-256 en conjunto con HMAC y la llave privada (key) que será proporcionada por el equipo de soporte. Continuación se proporciona una descripción detallada del funcionamiento de este proceso.
Descripción de los encabezados a Agregar
- x-scrty-content-sha256: Aplica un algoritmo SHA-256 al cuerpo (body) del request.
- x-scrty-date: Representa el tiempo actual en formato UTC (Tiempo Coordinado Universal), expresado en unixtime. Se establece un margen de 5 minutos de diferencia entre el tiempo del encabezado y el tiempo del servidor
- Autorization: "scrty :" seguido del cálculo de HMAC, que se detalla a continuación.
Cálculo de HMAC
El proceso de cálculo del hash HMAC se lleva a cabo mediante el algoritmo SHA-256. Este cálculo se realiza sobre la concatenación de los siguientes elementos y la llave privada:
method|Content-Type|x-scrty-content-sha256|x-scrty-date
Con el fin de aclarar más el funcionamiento, compartimos el código fuente en algunos lenguajes populares; pero si aún tienes dudas, no dudes en contactar al equipo de soporte.
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
class Program
{
static void Main()
{
// Fecha y hora automatizadas
long date = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
// Clave HMAC
string key = "XXXXXXXXXXXXXXXXXX";
string transactionBody = "{\"jsonProperty1\": \"value1\", \"jsonProperty2\": \"value2\"}";
string method = "POST";
string contentDigest = GetSha256Hash(transactionBody);
string contentType = "application/json";
// Nombre del host sin HTTPS
string host = "urldelendpoint";
// Encabezados
Dictionary<string, string> headers = new Dictionary<string, string>
{
{"Content-Type", contentType},
{"Accept", "application/json"},
{"x-scrty-content-sha256", contentDigest},
{"x-scrty-date", date.ToString()},
{"Authorization", "scrty :" + Convert.ToBase64String(HmacSha256(key, $"{method}|{contentType}|{contentDigest}|{date}"))}
};
// Solicitud HTTP
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://" + host );
request.Method = method;
request.ContentType = contentType;
foreach (var header in headers)
{
request.Headers.Add(header.Key, header.Value);
}
using (StreamWriter streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(transactionBody);
streamWriter.Flush();
streamWriter.Close();
}
// Respuesta HTTP
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
{
Console.WriteLine(streamReader.ReadToEnd());
}
}
static string GetSha256Hash(string input)
{
using (var sha256 = SHA256.Create())
{
byte[] hashBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(input));
StringSe adjuntan un Builder sb = new StringBuilder();
foreach (byte b in hashBytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
static byte[] HmacSha256(string key, string data)
{
using (HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key)))
{
return hmac.ComputeHash(Encoding.UTF8.GetBytes(data));
}
}
}
import hashlib
import hmac
import base64
import json
import requests
from datetime import datetime
def main():
# Fecha y hora automatizadas
date_scrty = int(datetime.utcnow().timestamp())
# Clave HMAC
key = "XXXXXXXXXXXXXXXXXX"
transaction_body = {"jsonProperty1": "value1", "jsonProperty2": "value2"}
method = "POST"
content_digest = get_sha256_hash(json.dumps(transaction_body))
content_type = "application/json"
# URL del endpoint
host = "urldelendpoint"
# Encabezados
headers = {
"Content-Type": content_type,
"Accept": "application/json",
"x-scrty-content-sha256": content_digest,
"x-scrty-date": str(date_scrty),
"Authorization": f"scrty : {base64.b64encode(hmac_sha256(key, f'{method}|{content_type}|{content_digest}|{date_scrty}').digest()).decode()}"
}
# Solicitud HTTP
response = requests.post(f"https://{host}", headers=headers, json=transaction_body)
# Imprimir respuesta HTTP
print(response.text)
def get_sha256_hash(input_string):
sha256 = hashlib.sha256()
sha256.update(input_string.encode("utf-8"))
return sha256.hexdigest()
def hmac_sha256(key, data):
return hmac.new(key.encode("utf-8"), data.encode("utf-8"), hashlib.sha256)
if __name__ == "__main__":
main()
Updated 3 months ago