Subversion Repositories SmartDukaan

Rev

Rev 13547 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

package in.shop2020.payment.service.handler;

import in.shop2020.payment.domain.Payment;
import in.shop2020.thrift.clients.config.ConfigClient;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.google.gson.reflect.TypeToken;

public class PayuPaymentHandler implements IPaymentHandler {

        private static Logger log = Logger.getLogger(Class.class);

        public static final String TXN_ID = "transactionId";
        public static final String PAYMENT_ID = "paymentId";
        public static final String AMOUNT = "amount";
        public static final String DATE_TIME = "dateTime";
        public static final String MODE = "mode";
        public static final String REF_NO = "referenceNo";
        public static final String TXN_TYPE = "transactionType";

        private static String apiUrl;
        private static String accountId;
        private static String secretKey;

        static {
                try {
                        ConfigClient cc = ConfigClient.getClient();
                        accountId = cc.get("payu_account_id");
                        secretKey = cc.get("payu_secret_key");
                        apiUrl = cc.get("payu_api_url");
                } catch (Exception e) {
                        log.error("Could not initialize Payu Handler!");
                }
        }
        
        public static Map<String, String> refundPayment(Payment payment, double amount){
                Map<String, String> params = new HashMap<String, String>();
                Map<String, String> resultMap = new HashMap<String, String>();
                String payuId = payment.getGatewayPaymentId();
                params.put("key", accountId);
                params.put("command", "cancel_refund_transaction");
                params.put("var1", payuId);
                params.put("var2", new Date().getTime() + "");
                params.put("var3", amount + "");
                try {
                        params.put("hash", getSecureHash(params));
                } catch (Exception e) {
                        resultMap.put(ERR_CODE, Errors.CONN_FAILURE.code);
                        resultMap.put(ERROR, Errors.CONN_FAILURE.message);
                        return resultMap;
                }
                String postResponse = "";
                try {
                        postResponse = executePost(apiUrl, getUrlParams(params));
                } catch (Exception e) {
                        resultMap.put(ERR_CODE, Errors.CONN_FAILURE.code);
                        resultMap.put(ERROR, Errors.CONN_FAILURE.message);
                        return resultMap;
                }
                log.info("postResponse====" + postResponse);
                JSONObject postMap = null;
                try {
                        postMap = new JSONObject(postResponse);
                
                        log.info("postMap.get(\"status\")=======" + postMap.get("status"));
                        if (0 == ((Integer)postMap.get("status")).intValue()) {
                                log.info("Some error occurred at Payu");
                                resultMap.put(ERR_CODE, Errors.CAPTURE_FAILURE.code);
                                resultMap.put(ERROR, (String)postMap.get("msg"));
                        } else if (1 == ((Integer)postMap.get("status")).intValue()){
                                System.out.println("in io block"); 
                                if(!JSONObject.NULL.equals(postMap.get("bank_ref_num"))){ 
                                        resultMap.put(REF_NO, (String) postMap.get("bank_ref_num"));
                                }
                                System.out.println("after bankrefnum"); 
                                if(postMap.get("txn_update_id")!= null) {
                                        resultMap.put("txn_update_id", (String)postMap.get("txn_update_id"));
                                }
                                System.out.println("after txn update"); 
                                if(postMap.get("request_id")!=null){
                                        resultMap.put("txn_update_id", (String)postMap.get("request_id"));
                                }
                                System.out.println("after request_id"); 
                                resultMap.put("mihpayid", ((Integer)postMap.get("mihpayid")).toString());
                                System.out.println("after mihpayid"); 
                                resultMap.put("msg", (String)postMap.get("msg"));
                        }
                } catch (JSONException e) {
                        log.error("Could not Parse json");
                        resultMap.put(ERR_CODE, Errors.CAPTURE_FAILURE.code);
                        resultMap.put(ERROR, "Could not parse refund");
                }
                log.info("Parsed refund response for payment" + payment.getId());
                return resultMap;
        }

        public static Map<String, String> captureTransaction(String paymentId,
                        String payuId) {
                Map<String, String> params = new HashMap<String, String>();
                Map<String, String> resultMap = new HashMap<String, String>();
                params.put("key", accountId);
                params.put("command", "capture_transaction");
                params.put("var1", payuId);
                params.put("var2", new Date().getTime() + "");
                try {
                        params.put("hash", getSecureHash(params));
                } catch (Exception e) {
                        resultMap.put(ERR_CODE, Errors.CONN_FAILURE.code);
                        resultMap.put(ERROR, Errors.CONN_FAILURE.message);
                        return resultMap;
                }
                String postResponse = "";
                try {
                        postResponse = executePost(apiUrl, getUrlParams(params));
                } catch (Exception e) {
                        resultMap.put(ERR_CODE, Errors.CONN_FAILURE.code);
                        resultMap.put(ERROR, Errors.CONN_FAILURE.message);
                        return resultMap;
                }
                GsonBuilder gsonBuilder = new GsonBuilder();
                gsonBuilder
                                .registerTypeAdapter(Object.class, new NaturalDeserializer());
                Gson gson = gsonBuilder.create();
                Type t = new TypeToken<Map<String,Object>>() {}.getType();
                Map<String, Object> postMap =  gson.fromJson(postResponse, t);
                if ("1".equals(postMap.get("status"))) {
                        resultMap.put(CAPTURE_TXN_ID, params.get("var2"));
                        resultMap.put(PAYMENT_ID, paymentId);
                        resultMap.put(CAPTURE_TIME, new SimpleDateFormat().format(new Date()));
                        resultMap.put(REF_NO, (String) postMap.get("bank_ref_num"));
                        log.info("Parsed capture response:");
                }
                if ("0".equals(postMap.get("status"))) {
                        resultMap.put(ERR_CODE, Errors.CAPTURE_FAILURE.code);
                        resultMap.put(ERROR, (String)postMap.get("msg"));
                }
                for(Entry<String, String> entry : resultMap.entrySet()){
                        log.info("Key: " + entry.getKey() + ", Value: " + entry.getValue());
                }
                return resultMap;

        }

        private static List<NameValuePair> getUrlParams(Map<String, String> params) {
                List<NameValuePair> pairs =  new ArrayList<NameValuePair>();
                for(Map.Entry<String, String> entry : params.entrySet()){
                        pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                return pairs;
        }

        private static String getSecureHash(Map<String, String> params)
                        throws NoSuchAlgorithmException {
                StringBuffer sb = new StringBuffer();
                String passString = sb.append(params.get("key")).append("|")
                                .append(params.get("command")).append("|")
                                .append(params.get("var1")).append("|").append(secretKey)
                                .toString();
                MessageDigest md = MessageDigest.getInstance("SHA-512");
                md.update(passString.getBytes(), 0, passString.getBytes().length);
                byte[] mdbytes = md.digest();
                // convert the byte to hex format method
                StringBuffer sb1 = new StringBuffer();
                for (int i = 0; i < mdbytes.length; i++) {
                        sb1.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16)
                                        .substring(1));
                }
                return sb1.toString();
        }

        public static String executePost(String targetURL,
                        List<NameValuePair> nameValuePairs) throws Exception {
                HttpClient client = new DefaultHttpClient();
                HttpPost post = new HttpPost(targetURL);
                post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = client.execute(post);
                BufferedReader rd = new BufferedReader(new InputStreamReader(response
                                .getEntity().getContent()));
                String line = "";
                StringBuffer sb = new StringBuffer();
                while ((line = rd.readLine()) != null) {
                        sb.append(line);
                }
                return sb.toString();
        }

        private static class NaturalDeserializer implements
                        JsonDeserializer<Object> {
                public Object deserialize(JsonElement json, Type typeOfT,
                                JsonDeserializationContext context) {
                        if (json.isJsonNull())
                                return null;
                        else if (json.isJsonPrimitive())
                                return handlePrimitive(json.getAsJsonPrimitive());
                        else if (json.isJsonArray())
                                return handleArray(json.getAsJsonArray(), context);
                        else
                                return handleObject(json.getAsJsonObject(), context);
                }

                private Object handlePrimitive(JsonPrimitive json) {
                        if (json.isBoolean())
                                return json.getAsBoolean();
                        else if (json.isString())
                                return json.getAsString();
                        else {
                                BigDecimal bigDec = json.getAsBigDecimal();
                                // Find out if it is an int type
                                try {
                                        bigDec.toBigIntegerExact();
                                        try {
                                                return bigDec.intValueExact();
                                        } catch (ArithmeticException e) {
                                        }
                                        return bigDec.longValue();
                                } catch (ArithmeticException e) {
                                }
                                // Just return it as a double
                                return bigDec.doubleValue();
                        }
                }

                private Object handleArray(JsonArray json,
                                JsonDeserializationContext context) {
                        Object[] array = new Object[json.size()];
                        for (int i = 0; i < array.length; i++)
                                array[i] = context.deserialize(json.get(i), Object.class);
                        return array;
                }

                private Object handleObject(JsonObject json,
                                JsonDeserializationContext context) {
                        Map<String, Object> map = new HashMap<String, Object>();
                        for (Map.Entry<String, JsonElement> entry : json.entrySet())
                                map.put(entry.getKey(),
                                                context.deserialize(entry.getValue(), Object.class));
                        return map;
                }
        }
        
        public static void main (String arg[]){
                String jsonText = "{\"amit\":0, \"babu\":{\"a\":null}, \"Raka\": null}";
/*              System.out.println(jsonText);
                GsonBuilder gsonBuilder = new GsonBuilder();
                gsonBuilder
                                .registerTypeAdapter(Object.class, new NaturalDeserializer());
                Gson gson = gsonBuilder.create();
                Type t = new TypeToken<Map<String,Object>>() {}.getType();
                Map<String, Object> postMap =  gson.fromJson(jsonText, t);
                Map<String, Object> postMap = (Map<String, Object>) gson.fromJson(
                                jsonText, Object.class);
                System.out.println(postMap);
                System.out.println(0 == ((Integer)postMap.get("amit")).intValue());*/
                try {
                        String postResponse = "{\"status\":1,\"msg\":\"Refund Request Queued\",\"request_id\":\"172046358\",\"bank_ref_num\":null,\"mihpayid\":251494242,\"error_code\":102}";
                        JSONObject postMap = new JSONObject(postResponse);
                        String a = "";
                        log.info("postMap.get(\"status\")=======" + postMap.get("status"));
                        if (0 == ((Integer)postMap.get("status")).intValue()) {
                                log.info("Some error occurred at Payu");
                                a= (String)postMap.get("msg");
                        } else if (1 == ((Integer)postMap.get("status")).intValue()){
                                System.out.println("in io block"); 
                                System.out.println(postMap.get("bank_ref_num").getClass());
                                if(postMap.get("bank_ref_num")!=null){ 
                                        a = (String) postMap.get("bank_ref_num");
                                }
                                System.out.println("after bankrefnum"); 
                                if(postMap.get("txn_update_id")!= null) {
                                        a = (String)postMap.get("txn_update_id");
                                }
                                System.out.println("after txn update"); 
                                if(JSONObject.NULL.equals(postMap.get("request_id"))){
                                        a = (String)postMap.get("request_id");
                                }
                                System.out.println("after request_id"); 
                                ((Integer)postMap.get("mihpayid")).toString();
                                System.out.println("after mihpayid"); 
                                a = (String)postMap.get("msg");
                        }
                } catch (JSONException e) {
                        System.out.println("in catch");
                }
        }
}