Rev 2334 | Rev 2707 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed
package in.shop2020.serving.services;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Random;import org.apache.log4j.Logger;import org.apache.thrift.TException;import in.shop2020.config.ConfigException;import in.shop2020.model.v1.order.LineItem;import in.shop2020.model.v1.order.Order;import in.shop2020.model.v1.order.Transaction;import in.shop2020.model.v1.order.TransactionServiceException;import in.shop2020.model.v1.user.ShoppingCartException;import in.shop2020.payments.Attribute;import in.shop2020.payments.Payment;import in.shop2020.payments.PaymentStatus;import in.shop2020.thrift.clients.PaymentServiceClient;import in.shop2020.thrift.clients.TransactionServiceClient;import in.shop2020.thrift.clients.config.ConfigClient;import com.aciworldwide.commerce.gateway.plugins.NotEnoughDataException;import com.aciworldwide.commerce.gateway.plugins.e24PaymentPipe;import com.aciworldwide.commerce.gateway.plugins.e24TranPipe;public class HdfcPaymentService implements IPaymentService {private static final long serialVersionUID = 1L;private static Logger log = Logger.getLogger(Class.class);private static String resourceFilePath;private static String aliasName;private static String responseURL;private static String errorURL;private static final String regex = "[^a-zA-Z0-9\\s\\-\\@\\/\\.]";private static final String replacement = " ";private static final int MAX_UDF_LENGTH = 30;private static final String currencyCode = "356";private String redirectURL;private e24PaymentPipe pipe = null;private double amount;private int gatewayId=1;private long paymentId;private enum ActionType{PURCHASE("1"),AUTH ("4"),CAPTURE("5");private String value;ActionType(String value) {this.value = value;}public String value(){return this.value;}}public HdfcPaymentService() {}static{try {resourceFilePath = ConfigClient.getClient().get("payment_resource_file_path");aliasName = ConfigClient.getClient().get("payment_alias_name");responseURL = ConfigClient.getClient().get("payment_response_url");errorURL = ConfigClient.getClient().get("payment_error_url");} catch (ConfigException e) {log.error("Unable to get data from config server.");}}public long createPayment(long currentCartId, long userId, long txnId, String paymentOption){log.info("Creating payment for the txn#: " + txnId + " for the user: " + userId + " for processing through HDFC");CommonPaymentService cps = new CommonPaymentService();if(!cps.createPayment(currentCartId, userId, txnId, gatewayId)){log.error("Error while creating the basic payment");return PAYMENT_NOT_CREATED;}paymentId = cps.getPaymentId();amount = cps.getAmount();try {initializePayment(paymentId, amount);} catch (ShoppingCartException e1) {log.error("Error while creating hdfc payment.");e1.printStackTrace();return PAYMENT_NOT_CREATED;} catch (TException e1) {log.error("Error while creating hdfc payment.");e1.printStackTrace();return PAYMENT_NOT_CREATED;}List<Attribute> attributes = null;try {attributes = getAttributesAndSetUdfs(txnId);attributes.add(new Attribute(IPaymentService.PAYMENT_METHOD, paymentOption));} catch (TransactionServiceException e1) {log.error("Error while setting udfs to payment.");e1.printStackTrace();return PAYMENT_NOT_CREATED;} catch (TException e1) {log.error("Error while setting udfs to payment.");e1.printStackTrace();return PAYMENT_NOT_CREATED;}PaymentServiceClient paymentServiceClient = null;try {paymentServiceClient = new PaymentServiceClient();} catch (Exception e) {log.error("Error while getting payment client");e.printStackTrace();return PAYMENT_NOT_CREATED;}try {//TODO: Put this in a timed block.short status = pipe.performPaymentInitialization();if(status != e24PaymentPipe.SUCCESS) {log.error("Error sending Payment Initialization Request: ");paymentServiceClient.getClient().updatePaymentDetails(paymentId, null, "", "", pipe.getErrorMsg(), "", "", "", "", PaymentStatus.INIT, "", attributes);redirectURL = errorURL + "?paymentId="+ paymentId + "&ErrorText="+pipe.getErrorMsg();return PAYMENT_NOT_CREATED;} else {log.info("Payment Initialization Request processed successfully for payment Id: " + paymentId);String paymentID = pipe.getPaymentId();paymentServiceClient.getClient().updatePaymentDetails(paymentId, paymentID, "", "", "", "", "", "", "", PaymentStatus.INIT, "", attributes);String payURL = pipe.getPaymentPage();redirectURL = payURL + "?PaymentID=" + paymentID;return paymentId;}} catch (NotEnoughDataException e) {log.error("Error while initializing payment.", e);}catch (Exception e) {log.error("Error while initializing payment.", e);}redirectURL = errorURL + "?paymentId="+paymentId + "?ErrorText=Error while initializing payment.";return PAYMENT_NOT_CREATED;}public static Map<String, String> capturePayment(Payment payment, String gatewayTxnId){String amount = "" + payment.getAmount();String gatewayPaymentId = payment.getGatewayPaymentId();log.info("Capturing amount: Rs " + amount + " for payment Id: " + gatewayPaymentId);//Prepare resultMap to elicit failure behaviour in case anything goes wrong.Map<String, String> resultMap = new HashMap<String, String>();resultMap.put(STATUS, "-2");e24TranPipe pipe = new e24TranPipe();pipe.setResourcePath(resourceFilePath);pipe.setAlias(aliasName);pipe.setAction(ActionType.CAPTURE.value());pipe.setAmt(amount);pipe.setTrackId("" + payment.getPaymentId());pipe.setMember("SAHOLIC");pipe.setCurrencyCode(currencyCode);pipe.setTransId(gatewayTxnId);//Check if the values have been set properlylog.info("Pipe Amount: " + pipe.getAmt());log.info("Pipe Action Code: " + pipe.getAction());log.info("Pipe Currency Code: " + pipe.getCurrencyCode());log.info("Pipe Track Id: " + pipe.getTrackId());log.info("Pipe Trans Id:" + pipe.getTransId());int captureStatus = e24TranPipe.FAILURE;try {captureStatus = pipe.performTransaction();log.info("Capture Status: " + captureStatus);log.info("Gateway Txn Status: " + pipe.getResult());log.info("Debug Msg: " + pipe.getDebugMsg());log.info("Auth: " + pipe.getAuth());log.info("Ref: " + pipe.getRef());log.info("TransId:" + pipe.getTransId());log.info("Amount: " + pipe.getAmt());resultMap.put(STATUS, "" + captureStatus);String result = pipe.getResult();resultMap.put(GATEWAY_STATUS, result.substring(0, Math.min(result.length(), 20)).trim()); //This will return the result of the transaction. (Successful or Failed)if(captureStatus != e24TranPipe.SUCCESS || !"CAPTURED".equals(result)){resultMap.put(ERROR, pipe.getErrorMsg()); // In case of any error, we only need to get the error message}else{resultMap.put(CAPTURE_AUTH_ID, pipe.getAuth()); // Unique ID generated by Authorizer of the transactionresultMap.put(CAPTURE_REF_ID, pipe.getRef()); // Unique reference number generated during the transactionresultMap.put(CAPTURE_TXN_ID, pipe.getTransId()); // Unique Transaction ID generated after every successful transactionresultMap.put(CAPTURE_AMNT, pipe.getAmt()); // Original Amount of the transaction}} catch (NotEnoughDataException e) {log.error("Unable to capture payment", e);resultMap.put(ERR_CODE, Errors.CONN_FAILURE.code);resultMap.put(ERROR, "Unable to capture transaction.");}return resultMap;}private List<Attribute> getAttributesAndSetUdfs(long txnId) throws TransactionServiceException, TException{StringBuilder orderDetails = new StringBuilder();StringBuilder billingAddress = new StringBuilder();String email = "";String contactNumber = "";//get udfsTransaction transaction;TransactionServiceClient transactionServiceClient = null;try {transactionServiceClient = new TransactionServiceClient();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}in.shop2020.model.v1.order.TransactionService.Client txnClient = transactionServiceClient.getClient();transaction = txnClient.getTransaction(txnId);orderDetails.append(transaction.getOrdersSize() + " ");for (Order order : transaction.getOrders()) {contactNumber= order.getCustomer_mobilenumber();email = order.getCustomer_email();billingAddress.append(" ");if(order.getCustomer_pincode()!=null){billingAddress.append(order.getCustomer_pincode());}if(order.getCustomer_city()!=null){billingAddress.append(" " + order.getCustomer_city());}if(order.getCustomer_address1()!=null){billingAddress.append(" " + order.getCustomer_address1());}if(order.getCustomer_address2()!=null){billingAddress.append(" " + order.getCustomer_address2());}if(order.getCustomer_state()!=null){billingAddress.append(" " + order.getCustomer_state());}for(LineItem line: order.getLineitems()){if(line.getBrand() != null){orderDetails.append(line.getBrand());}if(line.getModel_name() != null){orderDetails.append(line.getModel_name());}if(line.getModel_number() != null){orderDetails.append(line.getModel_number());}if(line.getColor() != null){orderDetails.append(line.getColor());}orderDetails.append(" ");}}Random random = new Random();String merchantInfo = ""+random.nextLong();String udf1 = formatUdf(orderDetails.toString());String udf2 = formatUdf(email);String udf3 = formatUdf(contactNumber);String udf4 = formatUdf(billingAddress.toString());String udf5 = merchantInfo;log.info("udf1:" + udf1);log.info("udf2:" + udf2);log.info("udf3:" + udf3);log.info("udf4:" + udf4);log.info("udf5:" + udf5);pipe.setUdf1(udf1); // UDF 1 - Order detailspipe.setUdf2(udf2); // UDF 2 - Email IDpipe.setUdf3(udf3); // UDF 3 - Contact Number.pipe.setUdf4(udf4); // UDF 4 - Billing Addresspipe.setUdf5(udf5); // UDF 5 - Merchant specificList<Attribute> attributes = new ArrayList<Attribute>();Attribute attribute1 = new Attribute("udf1",udf1);Attribute attribute2 = new Attribute("udf2",udf2);Attribute attribute3 = new Attribute("udf3",udf3);Attribute attribute4 = new Attribute("udf4",udf4);Attribute attribute5 = new Attribute("udf5",udf5);attributes.add(attribute1);attributes.add(attribute2);attributes.add(attribute3);attributes.add(attribute4);attributes.add(attribute5);return attributes;}private void initializePayment(long merchantPaymentId, double amounta) throws ShoppingCartException, TException{String amount;amount = (new Double(amounta)).toString();//Following is the code which initilize e24PaymentPipe with proper valuepipe=new e24PaymentPipe();pipe.setResourcePath(resourceFilePath); //mandatoryString as = pipe.getResourcePath();log.info("Resource= " +as);pipe.setAlias(aliasName); //mandatoryString ab=pipe.getAlias();log.info("Alias= " +ab);pipe.setAction(ActionType.AUTH.value()); //mandatoryString ac=pipe.getAction();log.info("Action= " +ac);pipe.setResponseURL( responseURL ); //mandatoryString at=pipe.getResponseURL();log.info("ResponseURL= "+at);pipe.setErrorURL( errorURL + "?paymentId=" + merchantPaymentId ); //mandatoryString ak=pipe.getErrorURL();log.info("ErrorURL= " + ak);pipe.setAmt(amount);String ap=pipe.getAmt();log.info("Amt= " + ap);pipe.setCurrency(currencyCode);String a=pipe.getCurrency();log.info("Currency= " + a);pipe.setLanguage("USA");String p=pipe.getLanguage();log.info("Language= "+ p);pipe.setTrackId((new Long(merchantPaymentId)).toString());}String formatUdf(String udfString){udfString = udfString.replaceAll(regex, replacement);if(udfString.length() > MAX_UDF_LENGTH){udfString = udfString.substring(0, MAX_UDF_LENGTH);}return udfString;}public String getRedirectUrl(){return this.redirectURL;}public static void main(String args[]){Payment payment = new Payment();payment.setPaymentId(216);payment.setAmount(40000);payment.setGatewayPaymentId("TESTSTSTS");//This test checks what happens when the txn id is left blankcapturePayment(payment, ""); //Result: !ERROR!-GW00205-Invalid Subsequent Transaction.//This test checks what happends with an invalid txn idcapturePayment(payment, "6022630101411740"); //Result: !ERROR!-GW00201-Transaction not found.//The next three tests require a valid AUTH transaction id.//This test checks what happens when we attempt to capture an amount greater than what was authorized.capturePayment(payment, "9644960021411730"); //Result: !ERROR!-GW00177-Failed Capture Greater Than Auth check.//This test checks what happens when we attempt to capture a valid transaction with the right amount. This transaction should be CAPTURED.payment.setAmount(21698);capturePayment(payment, "9644960021411730"); //Result: CAPTURED//This test tries to capture an already captured payment.capturePayment(payment, "9644960021411730"); //Result: !ERROR!-GW00177-Failed Capture Greater Than Auth check.}}