Monday 8 August 2016

Payment gateway with authorize .net

  [HttpPost]
        public ActionResult PaymentCreditCard(PaymentGatewayModel model)
        {
         

            sbLog = new StringBuilder();
            sbLog.Append("Start of PaymentCreditCard() Post method of PaymentGateway Controller");
            model.LstMonth = objCommonBLL.GetMonthList();
            model.LstYear = objCommonBLL.GetYearList();


            try
            {
                // By default, this sample code is designed to post to our test server for
                // developer accounts: https://test.authorize.net/gateway/transact.dll
                // for real accounts (even in test mode), please make sure that you are
                // posting to: https://secure.authorize.net/gateway/transact.dll

                String post_url = "https://test.authorize.net/gateway/transact.dll";

                Dictionary<string, string> post_values = new Dictionary<string, string>();
                //the API Login ID and Transaction Key must be replaced with valid values
                if (Session["EmailID"] != null)
                {
                    objMyAccount = objUserBLL.GetAccountDetailsByEmail(Session["EmailID"].ToString().Trim());
                }
                else
                {
                    TempData["UserMessage"] = "Please Enter Valid Email ID which you entered at registration Time";
                    RedirectToAction("Login", "UserAccount");
                }


                post_values.Add("x_login", "7pf2RTt5W69t");
                post_values.Add("x_tran_key", "35nbVPh6Z79R26ab");


                post_values.Add("x_delim_data", "TRUE");
                post_values.Add("x_delim_char", "|");
                post_values.Add("x_relay_response", "FALSE");

                post_values.Add("x_type", "AUTH_CAPTURE");
                post_values.Add("x_method", "CC");

                //Credit Card Number
                //post_values.Add("x_card_num", "4007000000027");
                post_values.Add("x_card_num", model.CreditCardNo.ToString().Trim());

                //Expiration Date Card Number
                //post_values.Add("x_exp_date", "0418");
                post_values.Add("x_exp_date", model.ExpiryMonth.ToString() + model.ExpiryYear.ToString());

                //Order Amount

                if (Session["SubscrAmount"] != null)
                {
                    post_values.Add("x_amount", Session["SubscrAmount"].ToString().Trim());
                }
                else
                {
                    if (objMyAccount.IsWholesaler)
                    {
                        post_values.Add("x_amount", ConfigurationManager.AppSettings["PremiumPlan"].ToString());
                    }
                    else
                    {
                        post_values.Add("x_amount", ConfigurationManager.AppSettings["BasicPlan"].ToString());
                    }

                }

                post_values.Add("x_description", "Sample Transaction");
                post_values.Add("x_first_name", objMyAccount.FirstName.Trim());
                post_values.Add("x_last_name", objMyAccount.LastName.Trim());
                post_values.Add("x_address", objMyAccount.Address);
                post_values.Add("x_zip", objMyAccount.ZipCode);
                post_values.Add("x_cust_id", objMyAccount.UserId.ToString());

                String post_string = "";

                foreach (KeyValuePair<string, string> post_value in post_values)
                {
                    post_string += post_value.Key + "=" +
                    HttpUtility.UrlEncode(post_value.Value) + "&";
                }
                post_string = post_string.TrimEnd('&');


                // create an HttpWebRequest object to communicate with Authorize.net
                HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(post_url);
                objRequest.Method = "POST";
                objRequest.ContentLength = post_string.Length;
                objRequest.ContentType = "application/x-www-form-urlencoded";

                // post data is sent as a stream
                StreamWriter myWriter = null;
                myWriter = new StreamWriter(objRequest.GetRequestStream());
                myWriter.Write(post_string);
                myWriter.Close();

                // returned values are returned as a stream, then read into a string
                String post_response;
                HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
                using (StreamReader responseStream = new StreamReader(objResponse.GetResponseStream()))
                {
                    post_response = responseStream.ReadToEnd();
                }
                // the response string is broken into an array
                // The split character specified here must match the delimiting character specified above
                Array response_array = post_response.Split('|');
                if (response_array.GetValue(0).ToString() == "1")
                {

                    model.ResponseCode = Convert.ToInt32(response_array.GetValue(0));
                    model.ResponseSubCode = Convert.ToInt32(response_array.GetValue(1));
                    model.ResponseReasonCode = Convert.ToInt32(response_array.GetValue(2));
                    model.ResponseResonText = response_array.GetValue(3).ToString();
                    model.AuthorizationCode = response_array.GetValue(4).ToString();
                    model.AVSResponse = response_array.GetValue(6).ToString();
                    model.PaymentTransactionId = response_array.GetValue(7).ToString();
                    model.InvoiceNumber = "INV" + objMyAccount.UserId;
                    model.Description = response_array.GetValue(8).ToString();
                    model.Amount = Convert.ToDecimal(response_array.GetValue(9));
                    model.PaymentMethod = response_array.GetValue(10).ToString();
                    model.TransactionType = response_array.GetValue(11).ToString();
                    model.CustomerID = "CUST" + objMyAccount.UserId;
                    model.FirstName = response_array.GetValue(13).ToString();
                    model.LastName = response_array.GetValue(14).ToString();
                    model.Company = response_array.GetValue(15).ToString();
                    model.Address = response_array.GetValue(16).ToString();
                    model.City = response_array.GetValue(17).ToString();
                    model.State = response_array.GetValue(18).ToString();
                    model.PostalCode = response_array.GetValue(19).ToString();
                    model.UserID = objMyAccount.UserId;
                    Session["UserId"] = objMyAccount.UserId;
                    Session["UserName"] = objMyAccount.UserName;
                    Session["IsWholeSaler"] = objMyAccount.IsWholesaler;

                    bool result = objUserBLL.InsertPaymentGateway(model);
                    if (result == true)
                    {
                        return RedirectToAction("Dashboard", "Home");
                    }
                    else
                    {
                        Session["UserId"] = null;
                        TempData["Error"] = response_array.GetValue(3).ToString();
                        model.LstMonth = objCommonBLL.GetMonthList();
                        model.LstYear = objCommonBLL.GetYearList();
                        return View(model);
                    }
                }
                else
                {
                    Session["UserId"] = null;
                    TempData["Error"] = response_array.GetValue(3).ToString();
                    model.LstMonth = objCommonBLL.GetMonthList();
                    model.LstYear = objCommonBLL.GetYearList();
                    return View(model);
                }
             

            }
            catch (Exception ex)
            {
                sbLog.Append("End of PaymentCreditCard() Post method of PaymentGateway Controller");
                sbLog.AppendLine();
                sbLog.Append("Error: " + ex);
                ErrorLog.GetDefault(null).Log(new Error(new InvalidOperationException("Log:" + sbLog.ToString())));

                return View("Error", new HandleErrorInfo(ex, "Payment through Credit Card info", "PaymentCreditCard"));

            }

         
        }

No comments:

Post a Comment