You are on page 1of 12

CODIGO: 0602022666003

MANUAL

PUNTO WEB CÓDIGO DE AUTENTICACIÓN

DE MENSAJE – ASP.NET

Procesos de Medios de Pago S.A. 


Documento confidencial para uso interno, prohibida su reproducción parcial o Página 1 de
total 11 Versión 1.00 Fecha de Publicación
24/06/2011
MANUAL PUNTO WEB: CÓDIGO
DE AUTENTICACIÓN DE MENSAJE –
ASP.NET
CODIGO: 0602022666003

HOJA DE CONTROL DE CAMBIOS

Antecedentes: (Si los hubiera)

Fecha Descripción del Cambio Versi Autorizado por:


ón
24-06- Publicación 1.00 M. Bibolotti
2011 J. Campos
B. Polanco
MANUAL PUNTO WEB: CÓDIGO
DE AUTENTICACIÓN DE MENSAJE –
ASP.NET
CODIGO: 0602022666003

CONTENIDO

METODOS DE AUTENTICACIÓN................................................................................................4
ESQUEMA DE SEGURIDAD:.................................................................................................. 4
CÓDIGO PARA ASP.NET:.............................................................................................................. 5
EJEMPLO DE CÓMO INVOCAR LA FUNCIÓN........................................................................................................ 7
EJEMPLO DEL ENVIÓ DE PARÁMETROS................................................................................................................ 7
EJEMPLO DE CÓMO INVOCAR LA FUNCIÓN........................................................................................................ 9
AMBIENTE DE PRUEBAS...........................................................................................................11

SOPORTE:......................................................................................................................................11
MANUAL PUNTO WEB: CÓDIGO
DE AUTENTICACIÓN DE MENSAJE –
ASP.NET
CODIGO: 0602022666003

METODOS DE AUTENTICACIÓN

ESQUEMA DE SEGURIDAD:

Matriz de variables que intervienen para el desarrollo de Message Autentication Code (MAC).

PLATAFORM ASP.N
AS et
INP DEFINICI SHA1-HMAC
UT ON
I1 Código de Comercio SI
I2 Nro. De Referencia SI
I3 Monto de la transacción SI
I4 Moneda de la transacción SI
I5 Fecha de la transacción SI
I6 Hora de la transacción SI
I7 Autogenerador Aleatorio. SI
I8 Código del Cliente SI
I9 Código de País de la Txn. SI
I10 Firma Digital
URLEncode(envío) Solo Resultado
Hash
METODO DE ENVIO DE INFORMACION POST
OUTPUT DEFINICION SHA1-HMAC
O1 Resultado de la Transacción SI
O2 Código de Autorización SI
O3 Número de Referencia SI
O4 Número de Cuotas
O5 Fecha de Primera Cuota.
O6 Moneda de cuota
O7 Monto de Cuota
O8 Moneda de Monto Total SI
O9 Monto Total SI
O10 Nro. De Referencia (ECO I2) SI
O11 Fecha de la transacción
O12 Hora de la transacción
O13 Código de Respuesta SI
O14 Código de País
O15 Nro. Tarjeta(Asterisqueada) SI
O16 SecureCode
O17 Mensaje de Respuesta(O13)
O18 Código del cliente (ECO del I8) SI
O19 Código de País de la Txn. SI
O20 Firma – HMAC SHA1
URLDecode Solo Resultado
Hash
MANUAL PUNTO WEB: CÓDIGO
DE AUTENTICACIÓN DE MENSAJE –
ASP.NET
CODIGO: 0602022666003
Nota: Para el método SHA1-HMAC, el O20 contiene el resultado MAC de los valores Output, que
Punto-Web envía al comercio, para efectos de validación.

El método de envió de los parámetros es por POST.

CÓDIGO PARAASP.NET:

Envío

El envío de los parámetros hacia Punto-Web, es por el método (MAC) SHA1-HMAC, donde el
requisito para el correcto funcionamiento es la Clave (KeyMerchant) proporcionada al Comercio por
Procesos MC Perú.

La función a utilizar para generar el MAC de los datos será la siguiente:

using System;
using
System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;

/// <summary>
/// Summary description for Signature
/// </summary>
public class Signature
{
public Signature()
{
//
// TODO: Add constructor logic here
//
}
/// <summary>
/// Helper function to compute a hash value
/// </summary>
/// <param name="hashAlgorithm">The hashing algoirhtm used. If that algorithm
needs some initialization, like HMAC and its derivatives, they should be initialized
prior to passing it to this function</param>
/// <param name="data">The data to hash</param>
/// <returns>a Base64 string of the hash value</returns>
private string ComputeHash(HashAlgorithm hashAlgorithm, string data)
{
if (hashAlgorithm == null)
{
throw new ArgumentNullException("hashAlgorithm");
}

if (string.IsNullOrEmpty(data))
MANUAL PUNTO WEB: CÓDIGO
DE AUTENTICACIÓN DE MENSAJE –
ASP.NET
CODIGO: 0602022666003
throw new ArgumentNullException("data");
}
byte[] dataBuffer = System.Text.Encoding.ASCII.GetBytes(data);
byte[] hashBytes = hashAlgorithm.ComputeHash(dataBuffer);

return Convert.ToBase64String(hashBytes);
}
/// <summary>
/// Generate the signature value based on the given signature base and hash
algorithm
/// </summary>
/// <param name="signatureBase">The signature based as produced by the
GenerateSignatureBase method or by any other means</param>
/// <param name="hash">The hash algorithm used to perform the hashing. If the
hashing algorithm requires initialization or a key it should be set prior to calling
this method</param>
/// <returns>A base64 string of the hash value</returns>
public string GenerateSignatureUsingHash(string signatureBase, HashAlgorithm
hash) {
return ComputeHash(hash, signatureBase);
}
/// <summary>
/// Generates a signature using the specified signatureType
/// </summary>
/// <param name="url">The full url that needs to be signed including its non
OAuth url parameters</param>
/// <param name="consumerKey">The consumer key</param>
/// <param name="consumerSecret">The consumer secret</param>
/// <param name="token">The token, if available. If not available pass null or
an empty string</param>
/// <param name="tokenSecret">The token secret, if available. If not available
pass null or an empty string</param>
/// <param name="httpMethod">The http method used. Must be a valid HTTP method
verb (POST,GET,PUT, etc)</param>
/// <param name="signatureType">The type of signature to use</param>
/// <returns>A base64 string of the hash value</returns>
public string GenerateSignature(string Data, string Key)
{
HMACSHA1 hmacsha1 = new HMACSHA1();
hmacsha1.Key = Encoding.ASCII.GetBytes(Key);
return GenerateSignatureUsingHash(Data, hmacsha1);
}
}

Donde:
Key = Clave proporcionada por Procesos MC Perú (32 Bytes)
Data = Es la concatenación de la información necesaria indicada en el cuadro inicial (Inputs)
teniendo en cuenta el orden de las variables, mas Key.
Nota: Aplicar la función URlEncode para el envió del resultado de la función.
MANUAL PUNTO WEB: CÓDIGO
DE AUTENTICACIÓN DE MENSAJE –
ASP.NET
CODIGO: 0602022666003

Ejemplo de cómo invocar la función:

//Objeto Signature
Signature sign = new
Signature(); string strFirma;
string[] arrDatos = new
string[10]; string strCadena;
//Key Merchant
string strKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
//Llenamos los inputs en un
arreglo arrDatos[0] =
txtComercio.Text; arrDatos[1] =
txtNroOC.Text; arrDatos[2] =
txtMonto.Text; arrDatos[3] =
txtMoneda.Text; arrDatos[4] =
txtFechaTxn.Text; arrDatos[5] =
txtHoraTxn.Text; arrDatos[6] =
txtAleatorio.Text; arrDatos[7] =
txtCodCliente.Text; arrDatos[8] =
txtCodPais.Text; arrDatos[9] =
strKey;
//Concatenando Inputs
strCadena = string.Join("", arrDatos);
//Generando MAC
strFirma = sign.GenerateSignature(strCadena,strKey);

Ejemplo del envío de parámetros

<html>
<body onload="document.frm.submit();">
<form id="frm" runat="server" method ="post" >
<asp:HiddenField ID="I1" runat="server" value= txtComercio.Text />
<asp:HiddenField ID="I2" runat="server" value= txtNroOC.Text />
<asp:HiddenField ID="I3" runat="server" value= txtMonto.Text />
<asp:HiddenField ID="I4" runat="server" value= txtMoneda.Text />
<asp:HiddenField ID="I5" runat="server" value= txtFechaTxn.Text />
<asp:HiddenField ID="I6" runat="server" value= txtHoraTxn.Text />
<asp:HiddenField ID="I7" runat="server" value= txtAleatorio.Text />
<asp:HiddenField ID="I8" runat="server" value= txtCodCliente.Text />
<asp:HiddenField ID="I9" runat="server" value= txtCodPais.Text />
<asp:HiddenField ID="I10" runat="server" value= Server.UrlEncode(strFirma) />
</form>
</body>
</html>
MANUAL PUNTO WEB: CÓDIGO
DE AUTENTICACIÓN DE MENSAJE –
ASP.NET
CODIGO: 0602022666003

Recepción:

La recepción de los parámetros desde Punto-Web, es por el método (MAC) SHA1-HMAC, donde el
requisito para el correcto funcionamiento es la Clave (KeyMerchant) proporcionada al Comercio por
Procesos MC Perú.

La función a utilizar para generar el MAC de los datos será la siguiente:

using System;
using
System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;

/// <summary>
/// Summary description for Signature
/// </summary>
public class Signature
{
public Signature()
{
//
// TODO: Add constructor logic here
//
}
/// <summary>
/// Helper function to compute a hash value
/// </summary>
/// <param name="hashAlgorithm">The hashing algoirhtm used. If that algorithm
needs some initialization, like HMAC and its derivatives, they should be initialized
prior to passing it to this function</param>
/// <param name="data">The data to hash</param>
/// <returns>a Base64 string of the hash value</returns>
private string ComputeHash(HashAlgorithm hashAlgorithm, string data)
{
if (hashAlgorithm == null)
{
throw new ArgumentNullException("hashAlgorithm");
}

if (string.IsNullOrEmpty(data))
{
throw new ArgumentNullException("data");
}
byte[] dataBuffer = System.Text.Encoding.ASCII.GetBytes(data);
byte[] hashBytes = hashAlgorithm.ComputeHash(dataBuffer);

return Convert.ToBase64String(hashBytes);
}
/// <summary>
/// Generate the signature value based on the given signature base and hash
algorithm
/// </summary>
/// <param name="signatureBase">The signature based as produced by the
GenerateSignatureBase method or by any other means</param>
MANUAL PUNTO WEB: CÓDIGO
DE AUTENTICACIÓN DE MENSAJE –
ASP.NET
CODIGO: 0602022666003
hashing algorithm requires initialization or a key it should be set prior to calling
this method</param>
/// <returns>A base64 string of the hash value</returns>
public string GenerateSignatureUsingHash(string signatureBase, HashAlgorithm
hash)
{
return ComputeHash(hash, signatureBase);
}
/// <summary>
/// Generates a signature using the specified signatureType
/// </summary>
/// <param name="url">The full url that needs to be signed including its non
OAuth url parameters</param>
/// <param name="consumerKey">The consumer key</param>
/// <param name="consumerSecret">The consumer seceret</param>
/// <param name="token">The token, if available. If not available pass null or
an empty string</param>
/// <param name="tokenSecret">The token secret, if available. If not available
pass null or an empty string</param>
/// <param name="httpMethod">The http method used. Must be a valid HTTP method
verb (POST,GET,PUT, etc)</param>
/// <param name="signatureType">The type of signature to use</param>
/// <returns>A base64 string of the hash
value</returns> public string GenerateSignature(string
Data, string Key)
{
HMACSHA1 hmacsha1 = new HMACSHA1();
hmacsha1.Key = Encoding.ASCII.GetBytes(Key);
return GenerateSignatureUsingHash(Data, hmacsha1);
}
}

Donde:
Key = Clave proporcionada por Procesos MC Perú (32 Bytes)
Data = Es la concatenación de la información necesaria indicada en el cuadro inicial (Outputs)
teniendo en cuenta el orden de las variables, mas Key.
Nota: Aplicar la función URlDecode para el Hash Recibido (O20)

Ejemplo de cómo invocar la función:

//Validamos si la txn fue


Autorizada if (O1 == “A”)
{
//Objeto Signature
Signature sign = new
Signature(); string strFirma;
string[] arrDatos = new
string[10]; string strCadena;
//Key Merchant
string strKey = " XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ";
//Hash Pasarela de Pagos
string HashPuntoWeb = Server.UrlDecode(O20);//HashSha1 PuntoWeb
string[] arrDatos = new string[10];
arrDatos[0] = O1; //Resultado
arrDatos[1] = O2; //Código Autorización
arrDatos[2] = O3; //Nro. Referencia
arrDatos[3] = 08; //Moneda
arrDatos[4] = 09; //Monto
arrDatos[5] = O10; //Nro. Orden
arrDatos[6] = 013; //código Respuesta
arrDatos[7] = 015; //Tarjeta Crédito(Asterisqueada)
arrDatos[8] = 018; //Código Cliente
arrDatos[9] = 019; //Código País
arrDatos[10] = $KeyMerchant;//KeyMerchant(32 BYTES)

//Concatenando Inputs
MANUAL PUNTO WEB: CÓDIGO
DE AUTENTICACIÓN DE MENSAJE –
ASP.NET
CODIGO: 0602022666003
strCadena = string.Join("", arrDatos);

//Generando MAC
strFirma = sign.GenerateSignature(strCadena,strKey);

//Validación de Hash
if (HashPuntoWeb == $ strFirma)
{
//Hash Valido
}
else
{
//Hash Inválido
}
}
else
{
//TRANSACCION DENEGADA
}

Procesos de Medios de Pago S.A. 


Documento confidencial para uso interno, prohibida su reproducción parcial o Página 10 de
total 11 Versión 1.00 Fecha de Publicación
24/06/2011
MANUAL PUNTO WEB: CÓDIGO
DE AUTENTICACIÓN DE MENSAJE –
ASP.NET
CODIGO: 0602022666003

AMBIENTE DE PRUEBAS

 Cuando el Comercio tenga desarrollado la parte de integración, podrá solicitar hacer las
pruebas con el ambiente de desarrollo.
 Las pruebas con el ambiente de desarrollo deben ser solicitadas con 48 horas de anticipación para
definir una ventana de prueba para el Comercio.
 El ambiente de pruebas no se encuentra las 24 horas disponibles para el Comercio, se deben
hacer coordinaciones previas para verificar la disponibilidad.

SOPORTE:

Para ayuda y consulta con respecto a este documento y/o integración a Punto-Web, puede
contactarse al siguiente mail:

Soporte Pasarela de Pagos


soporte.puntoweb@mc.com.
pe

You might also like