Snippets

EasyPaymentGateway EPG Java integration

Created by Ruben Fernandez

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.easypaymentsgateway.exceptions.EncryptionException;
import com.easypaymentsgateway.exceptions.EncryptionException.ErrorCode;
import com.easypaymentsgateway.utils.EncryptionUtils;

public class EPGJavaIntegration {

	private static final String ENDPOINT = "http://staging.easypaymentgateway.com/EPGCheckout/rest/online/tokenize";
	private static final String MID = "XXXXX";
	private static final String PARAMETERS = "YYYY";
	private static final String MERCHANT_PASSWORD = ""; // Merchant password or MD5 merchant password
	private static final String MD5_MERCHANT_PASSWORD = ""; // Merchant password or MD5 merchant password


	private static final String AES = "AES";
	private static final String MD5 = "MD5";
	private static Logger logger = LoggerFactory.getLogger(API.class);

	public static void main(String[] args) {
		logger.info("URL: " + new API(MID, 
				PARAMETERS, 
				MERCHANT_PASSWORD,MD5_MERCHANT_PASSWORD).tokenizer());
		

	}
	
	private String mid;
	private String params;
	private String passwordkey;
	private String mD5passwordkey;

	public EPGJavaIntegration(String mid, String params, String passwordkey, String mD5passwordkey) {
		this.mid = mid;
		this.params = params;
		this.passwordkey = passwordkey;
		this.mD5passwordkey = mD5passwordkey;
	}

	public String tokenizer(){
		String urlDestination = "";
		try {
			urlDestination = retrieveUrlToRedirect(
					encrypt(params, passwordkey==""?mD5passwordkey:hashMessage(passwordkey, MD5)),
					EncryptionUtils.hashMessage(params, EncryptionUtils.SHA256),
					mid);
		} catch (IOException e) {
			logger.error(
					"Error when trying to encrypt params" + e.getMessage(), e);
		}
		return urlDestination;
	}

	/**
	 * Encrypts using AES algorithm
	 * 
	 * @param input
	 * @param key
	 * @return
	 */
	public String encrypt(String input, String key) {
		byte[] crypted = null;
		try {
			SecretKeySpec skey = new SecretKeySpec(key.getBytes(), AES);
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, skey);
			crypted = cipher.doFinal(input.getBytes());
		} catch (Exception e) {
			logger.error(e.toString());
		}
		return new String(Base64.encodeBase64(crypted));
	}

	/**
	 * Decrypts using AES algorithm
	 * 
	 * @param input
	 * @param key
	 * @return
	 */
	public String decrypt(String input, String key) {
		byte[] output = null;
		try {
			SecretKeySpec skey = new SecretKeySpec(key.getBytes(), AES);
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			cipher.init(Cipher.DECRYPT_MODE, skey);
			output = cipher.doFinal(Base64.decodeBase64(input));
		} catch (Exception e) {
			logger.error(e.toString());
		}
		return new String(output);
	}

	/**
	 * method used to retrieve the session token supplied byEPG
	 */
	private String retrieveUrlToRedirect(String encryptedParams,
			String integrityCheck, String mid) throws IOException {
		String urlToRedirect;
		String url = ENDPOINT;

		// Build request body
		params = "encrypted=" + URLEncoder.encode(encryptedParams, "UTF-8")
				+ "&integrityCheck="
				+ URLEncoder.encode(integrityCheck, "UTF-8") + "&merchantId="
				+ URLEncoder.encode(mid, "UTF-8");

		urlToRedirect = httpCall(url);

		return urlToRedirect;
	}

	/**
	 * method used to make a http call
	 */
	private String httpCall(String destination) throws IOException {
		// Create connection
		URL url = new URL(destination);
		URLConnection urlConnection = url.openConnection();
		urlConnection.setDoInput(true);
		urlConnection.setDoOutput(true);
		urlConnection.setUseCaches(false);

		// Create I/O streams
		OutputStreamWriter outStream = new OutputStreamWriter(
				urlConnection.getOutputStream());

		// Send request
		outStream.write(params);
		outStream.flush();

		// Get Response
		BufferedReader rd = new BufferedReader(new InputStreamReader(
				urlConnection.getInputStream()));

		String urlToRedirect = rd.readLine();

		outStream.close();

		return urlToRedirect;
	}

	public String hashMessage(String message, String algorithm) {
		logger.debug("init - hashMessage");

		byte[] digest = null;
		byte[] buffer = message.getBytes();

		MessageDigest messageDigest;

		try {

			messageDigest = MessageDigest.getInstance(algorithm);
			messageDigest.reset();
			messageDigest.update(buffer);

			digest = messageDigest.digest();

		} catch (NoSuchAlgorithmException e) {

			logger.error("Internal error found");

			throw new EncryptionException(
					ErrorCode.UNABLE_TO_FIND_HASH_ALGORITHM,
					"Internal error found");
		}

		logger.debug("end - hashMessage");
		return toHexadecimal(digest);
	}

	private String toHexadecimal(byte[] digest) {
		logger.debug("init - toHexadecimal");

		String hash = "";

		for (byte aux : digest) {
			int b = aux & 0xff;

			if (Integer.toHexString(b).length() == 1)
				hash += "0";

			hash += Integer.toHexString(b);
		}

		logger.debug("end - toHexadecimal");
		return hash;
	}

}

Comments (2)

  1. Daniel Glenn

    This is useful, but may I suggest these improvements:

    1. there remain reference to API which I think should be changed to EPGJavaIntegration.
    2. Would be good to have an example that compiles standalone - i.e. we (a merchant) does not have access to the referenced EncryptionException, ErrorCode, nor EncryptionUtils classes.

    It isn't a big deal to correct these myself, but it would be nice if this example could have these tweaks to make it working code.

    1. Ruben Fernandez

      Hi Daniel,

      Firstly thanks for your message. We will note internally and we will update the snippets with the details that your mentioned. We created this link internally but at the end we shared with some clients.

      Regards, Ruben

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.