PayUMoney Integration in MVC and calling using ajax - c#

On button click I want the user to redirect to payumoney gateway and if payment has been done successfully, the data of user to be store in database and redirect user to success page vice a versa..
Currently I am saving data using AJAX call and redirect user on ajax success:function.
AJAX
$('#payNowButton').on("click", function () {
var total = $('#main_total_s5').html();
console.log("Total : " + total);
$.ajax({
url: '/Home/Demo?total=' + total, //Demo method in Home Controller is for payumoney payment gateway.
type: "POST",
data: total,
async: false,
success: function (result) {
window.location.href = result;
if (result > 0) {
PlaceOrder(); //after successful payment, it will call this function to save data in database.
window.location.href = '#Url.Action("Sucess", "Home")';
}
else {
alert("Some error occurred." + result);
}
},
error: function (result) {
window.location.href = '#Url.Action("Failure", "Home")';
}
});
});
Controller
[HttpPost]
public void Demo(OrderCustom orderCustom)
{
string firstName = "";
string amount = "";
string productInfo = "";
string email = "";
string phone = "";
string surl;
string furl;
RemotePost myremotepost = new RemotePost();
string key = "";
string salt = "";
//posting all the parameters required for integration.
myremotepost.Url = "https://secure.payu.in/_payment";
myremotepost.Add("key", "");
string txnid = Generatetxnid();
myremotepost.Add("txnid", txnid);
myremotepost.Add("amount", amount);
myremotepost.Add("productinfo", productInfo);
myremotepost.Add("firstname", firstName);
myremotepost.Add("phone", phone);
myremotepost.Add("email", email);
myremotepost.Add("surl", "http://localhost:/Home/Sucess");//Change the success url here depending upon the port number of your local system.
myremotepost.Add("furl", "http://localhost:/Home/Failure");//Change the failure url here depending upon the port number of your local system.
myremotepost.Add("service_provider", "payu_paisa");
string hashString = key + "|" + txnid + "|" + amount + "|" + productInfo + "|" + firstName + "|" + email + "|||||||||||" + salt;
string hash = Generatehash512(hashString);
myremotepost.Add("hash", hash);
myremotepost.Post();
}
public class RemotePost
{
private System.Collections.Specialized.NameValueCollection Inputs = new System.Collections.Specialized.NameValueCollection();
public string Url = "";
public string Method = "post";
public string FormName = "form1";
public void Add(string name, string value)
{
Inputs.Add(name, value);
}
public void Post()
{
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.Write("<html><head>");
System.Web.HttpContext.Current.Response.Write(string.Format("</head><body onload=\"document.{0}.submit()\">", FormName));
System.Web.HttpContext.Current.Response.Write(string.Format("<form name=\"{0}\" method=\"{1}\" action=\"{2}\" >", FormName, Method, Url));
for (int i = 0; i < Inputs.Keys.Count; i++)
{
System.Web.HttpContext.Current.Response.Write(string.Format("<input name=\"{0}\" type=\"hidden\" value=\"{1}\">", Inputs.Keys[i], Inputs[Inputs.Keys[i]]));
}
System.Web.HttpContext.Current.Response.Write("</form>");
System.Web.HttpContext.Current.Response.Write("</body></html>");
System.Web.HttpContext.Current.Response.End();
}
}
When I click on button it shows this error :
Error Image

I have faced the same problem yesterday. What I did i, I removed myremotepost.Add("service_provider", "payu_paisa"); and It worked!.
Also check the URL once, if you are doing it on test server then the URL would be https://test.payu.in/_payment
"Key" and "SALT" value cannot be blank, these values will be shared to you by payumoney itself.
string key = "";
string salt = "";

myremotepost.Add("service_provider", "payu_paisa");
This is Mandatory Field, Recently I am contacting with help desk they are asking for some customization. Then it will work

Related

C# MVC stops after model execution

I have a problem that I can't understand:
My ajax sends information to my controller
function guardar_stag() {
$.ajax({
url: '/Staging/guardar_stag_bd',
data: "{'po':'" + po + "','estilo':'" + estilo + "','size':'" + size + "','quantity':'" + quantity + "','employee':'" + employee + "','fabric_percent':'" + fabric_percent + "','country':'" + country + "','color':'" + color + "','comentario':'" + comentarios + "'}",
contentType: 'application/json',
dataType: 'json',
type: 'post',
success: function (result) {
//IT DOESN'T GET HERE
}
});
}
Then I handle the information in my controller, it takes all the values
[HttpPost]
public JsonResult guardar_stag_bd(string po, string estilo, string size, string quantity, string employee, string fabric_percent, string country, string color, string comentario)
{
string[] tallas = size.Split('*'), cantidades = quantity.Split('*'), empleados = employee.Split('*'), porcentajes = fabric_percent.Split('*'), paises = country.Split('*'), colores = color.Split('*');
int total = 0, id_size, id_color, id_pais, id_percent;
int summary = ds.buscar_id_summary(po, estilo);
for (int i = 1; i < cantidades.Length; i++)+= Convert.ToInt32(cantidades[i]);
}
int id_empleado;
ds.guardar_stag_bd(po, estilo, total, Convert.ToInt32(Session["id_usuario"]), summary, comentario);
int id_stag = ds.obtener_ultimo_stag();
for (int i = 1; i < cantidades.Length; i++){
id_empleado = stag.obtener_id_empleado(empleados[i]);
id_size = consultas.buscar_talla(tallas[i]);
id_color = consultas.buscar_color(colores[i]);
id_pais = consultas.buscar_id_pais(paises[i]);
id_percent = consultas.buscar_percent(porcentajes[i]);
stag.guardar_yarn(id_stag.ToString(), id_stag.ToString());
}
//FOR ENDS BUT NEVER GO TO THE NEXT LINE
Session["id_staging"] = id_stag;
return Json("0", JsonRequestBehavior.AllowGet);
}
I have to insert information into my DB with guardar_yarn but even after I go line by line in the model, it doesn't show any error nor does it insert, after the Dispose() it just ends and does not return to return Json line
public void guardar_yarn(string staging, string talla)
{
Conexion con = new Conexion();
try
{
SqlCommand com = new SqlCommand();
com.Connection = con.AbrirConexion();
com.CommandText = "INSERT INTO yarn(yarn) values('"+ staging+"') ";
com.ExecuteNonQuery();
}
finally { con.CerrarConexion(); con.Dispose(); }
//it stops after this line and goes to the html page
}
Sorry for my poor explanation, English is not my first language. Thanks

C# page keeps sending old data

So I hava a page where the user gives data for the app to send it to a database.
When the user clicks on next the app navigates to the next page. But when the user goes back and edits the data the app still saves the old data from the first input to the database.
For example:
Name : Jon Do
The user made a mistake and goes to the previous pageL
Name : John Doe
The user clicks next and the data gets saved to the database. But except of saving the new data "John Doe" it sends the old data, "Jon Do". This, ofcourse, should not happen. I have no clue why this happens.
Here is my C# code of the page where the user should give his/her data
private void btnNext_Click(object sender, RoutedEventArgs e)
{
if (ckbGegevens.IsChecked == false)
{
try
{
dt.saveData = true;
dt.bedrijfsNaam = txxBvName.Text;
dt.contactPersoon = txxContPersn.Text;
dt.telNummer = Convert.ToInt32(txxTelNr.Text);
dt.eMail = txxEMail.Text;
dt.land = txxLand.Text;
dt.plaats = txxPlaats.Text;
dt.postcode = txxPostCode.Text;
postToJson.post("bvg");
this.NavigationService.Navigate(new Doelen());
}
catch (Exception)
{
MessageBox.Show("Er ontbreken gegevens!\nOf u heeft ongeldige gegevens ingevuld!");
}
}
else
{
try {
dt.bedrijfsNaam = txxBvName.Text;
dt.contactPersoon = txxContPersn.Text;
dt.telNummer = Convert.ToInt32(txxTelNr.Text);
dt.eMail = txxEMail.Text;
dt.land = txxLand.Text;
dt.plaats = txxPlaats.Text;
dt.postcode = txxPostCode.Text;
dt.saveData = false;
MessageBox.Show("Uw gegevens worden niet opgeslagen.\nVink voor optimaal gebruik deze functie aan.");
this.NavigationService.Navigate(new Doelen());
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
This is how I save it to the database:
static string bedrijfsNaam = dt.bedrijfsNaam;
static string ContPers = dt.contactPersoon;
static int TelNum = dt.telNummer;
static string email = dt.eMail;
static string Land = dt.land;
static string Plaats = dt.plaats;
static string PostCode = dt.postcode;
static string json;
static string b64encode;
public postToJson(string reqCat)
{
}
public static void post(string reqCat)
{
if (reqCat == "bvg")
{
json = "{\"bedrijfsNaam\":\"" + bedrijfsNaam + "\"," +
"\"ContPers\":\"" + ContPers + "\"," +
"\"TelNum\":\"" + TelNum + "\"," +
"\"email\":\"" + email + "\"," +
"\"Land\":\"" + Land + "\"," +
"\"Plaats\":\"" + Plaats + "\"," +
"\"PostCode\":\"" + PostCode + "\"}";
var b64bytes = System.Text.Encoding.UTF8.GetBytes(json);
b64encode = System.Convert.ToBase64String(b64bytes);
var data = new NameValueCollection();
data["b64string"] = b64encode;
data["filename"] = dt.bedrijfsNaam;
using (WebClient client = new WebClient())
{
var sendB64 = client.UploadValues("http://" + ConfigurationManager.AppSettings["scripturi"].ToString() + "SalesKicker.php", "POST", data);
}
}
}
The problem isn't in the PHP script so I don't have to post that script. I know this because I printed out the result of the JSON. Which always has the data from the first input.
Can someone please tell me what is going on here?
The assignments seem to be done in the declaration of the static class, thereby they will only happen once and you don't know when. Therefore you should put these in a separate method:
static string bedrijfsNaam = dt.bedrijfsNaam;
static string ContPers = dt.contactPersoon;
static int TelNum = dt.telNummer;
static string email = dt.eMail;
static string Land = dt.land;
static string Plaats = dt.plaats;
static string PostCode = dt.postcode;
And then call that method in the post method.
E.g.
private static void updateData() {
bedrijfsNaam = dt.bedrijfsNaam;
ContPers = dt.contactPersoon;
TelNum = dt.telNummer;
email = dt.eMail;
Land = dt.land;
Plaats = dt.plaats;
PostCode = dt.postcode;
}

Post Redirect to URL with post data

I am working on a post redirect for a payment provider and trying to pass form data to their secure URL.
I am doing this in kentico 8 by using their custom payment gateway method as shown here https://docs.kentico.com/display/K8/Creating+a+custom+payment+gateway
So in the custom payment class I prepared the data to be passed to the payment provider in a 'Form' format with hidden fields using this tutorial http://www.codeproject.com/Articles/37539/Redirect-and-POST-in-ASP-NET
However I am not able to figure out on how to redirect to the secure URL with the form data?
Here is my code so far.
I have tried Response.Redirect however it is a GET function instead of POST.
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Configuration;
using CMS;
using CMS.Base;
using CMS.EcommerceProvider;
using CMS.Helpers;
using System.Security.Cryptography;
using System.Web;
using System.Web.Security;
using System.Text;
using System.IO;
using System.Net;
using System.Web.UI;
[assembly: RegisterCustomClass("CustomGateway", typeof(CustomGateway))]
public class CustomGateway : CMSPaymentGatewayProvider
{
/// <summary>
/// Process payment.
/// </summary>
public override void ProcessPayment()
{
// Get payment gateway url
string url = "https://epage.payandshop.com/epage.cgi";
if (url != "")
{
NameValueCollection postData = getRealexData();
RedirectAndPOST(url, postData);
}
else
{
// Show error message - payment gateway url not found
ErrorMessage = "Unable to finish payment: Payment gateway url not found.";
// Update payment result
PaymentResult.PaymentDescription = ErrorMessage;
PaymentResult.PaymentIsCompleted = false;
// Update order payment result in database
UpdateOrderPaymentResult();
}
}
public static void RedirectAndPOST(string destinationUrl, NameValueCollection data)
{
//Prepare the Posting form
string strForm = PreparePOSTForm(destinationUrl, data);
HttpContext.Current.Response.Write(strForm);
HttpContext.Current.Response.End();
}
private static String PreparePOSTForm(string url, NameValueCollection data)
{
//Set a name for the form
string formID = "PostForm";
//Build the form using the specified data to be posted.
StringBuilder strForm = new StringBuilder();
strForm.Append("<form id=\"" + formID + "\" name=\"" +
formID + "\" action=\"" + url +
"\" method=\"POST\">");
foreach (string key in data)
{
strForm.Append("<input type=\"hidden\" name=\"" + key +
"\" value=\"" + data[key] + "\">");
}
strForm.Append("</form>");
//Build the JavaScript which will do the Posting operation.
StringBuilder strScript = new StringBuilder();
strScript.Append("<script language=\"javascript\">");
strScript.Append("var v" + formID + " = document." +
formID + ";");
strScript.Append("v" + formID + ".submit();");
strScript.Append("</script>");
//Return the form and the script concatenated.
//(The order is important, Form then JavaScript)
return strForm.ToString() + strScript.ToString();
}
public NameValueCollection getRealexData()
{
//format the date expected by Realex
string timestamp = RealexDateFormatter.DateFormatForRealex();
//take the MerchantID and Shared Secret from the web.config
string merchantid = ConfigurationManager.AppSettings["RealexMerchantID"];
string secret = ConfigurationManager.AppSettings["RealexSecret"];
// Order Info
int orderid = ShoppingCartInfoObj.OrderId;
string stringorderid = Convert.ToString(orderid);
string curr = ShoppingCartInfoObj.Currency.CurrencyCode;
double amount = ShoppingCartInfoObj.TotalPrice;
amount = Convert.ToInt32(amount);
string prepareMD5 = timestamp + "." + merchantid + "." + orderid + "." + amount + "." + curr;
//generate the md5 Hash
MD5 md5 = new MD5CryptoServiceProvider();
string temp1 = GetMD5Hash(prepareMD5);
temp1 = temp1.ToLower();
string temp2 = temp1 + "." + secret;
string md5hash = GetMD5Hash(temp2);
md5hash = md5hash.ToLower();
NameValueCollection data = new NameValueCollection();
data.Add("MERCHANT_ID", merchantid);
data.Add("ORDER_ID", stringorderid);
data.Add("CURRENCY", curr);
data.Add("AMOUNT", amount.ToString());
data.Add("TIMESTAMP", timestamp);
data.Add("MD5HASH", md5hash);
data.Add("AUTO_SETTLE_FLAG", "1");
return data;
}
public static String GetMD5Hash(String TextToHash)
{
//Check wether data was passed
if ((TextToHash == null) || (TextToHash.Length == 0))
{
return String.Empty;
}
//Calculate MD5 hash
MD5 md5 = new MD5CryptoServiceProvider();
// Create a new Stringbuilder to collect the bytes
// and create a string.
byte[] data = md5.ComputeHash(Encoding.UTF8.GetBytes(TextToHash));
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
return sBuilder.ToString();
}
}
Take a look at this answer from a similar question. I would recommend using Method 3 in that answer. By creating an asynchronous call, you could wait for a response back and either redirect on a successful response with Response.Redirect(), or notify the user of any errors.

How to call a JavaScript function multiple times in a loop on page reload with ASP.NET

I'm using the local database functionality in Chrome and Safari and what I do when I want to save this to a remote database is to create a hidden textfield and then using JSON to stringify each row. In the code behind I then parse each JSON object and insert it into the list. What I want to do now is to delete these rows from the local database. I have a JavaScript function called deletePatient:
function deletePatient(patientID) {
MaRDB.transaction(
function (transaction) {
transaction.executeSql("DELETE FROM Patients WHERE id = " + patientID + ";");
}
);
}
I then call this function from the code behind if the insert was successfull
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Delete", "<script language='javascript'>$(document).ready(function() {deletePatient(" + id + ");});</script>");
However, it only deletes the patient with the lowest ID (the first JSON object). When I step through the code it goes back to that code for each ID but only deletes one. If I try with an alert it also only shows one ID even though it iterates through the code N number of times. I guess it's some kind of conflict with postback and executing a JavaScript function here but is it possible to solve?
protected void btnSave_Click(object sender, EventArgs e)
{
bool successfullySent = false;
SharePointConnection();
int count = Convert.ToInt32(txtRows.Text);
for (int i = 0; i <= count; i++)
{
string p = String.Format("{0}", Request.Form["hiddenField" + i]).ToString();
JObject o = JObject.Parse(p);
id = (int)o["id"];
string name = (string)o["name"];
string address = (string)o["address"];
string city = (string)o["city"];
string state = (string)o["state"];
string zip = (string)o["zip"];
string country = (string)o["country"];
string phone = (string)o["phone"];
StringBuilder sb_method = new StringBuilder();
sb_method.Append("<Method ID='1' Cmd='New'>");
sb_method.Append("<Field Name='Title'>" + name + "</Field>");
sb_method.Append("<Field Name='Address'>" + address + "</Field>");
sb_method.Append("<Field Name='City'>" + city + "</Field>");
sb_method.Append("<Field Name='State'>" + state + "</Field>");
sb_method.Append("<Field Name='ZIP'>" + zip + "</Field>");
sb_method.Append("<Field Name='Country'>" + country + "</Field>");
sb_method.Append("<Field Name='Phone'>" + phone + "</Field>");
sb_method.Append("</Method>");
XmlDocument x_doc = new XmlDocument();
XmlElement xe_batch = x_doc.CreateElement("Batch");
xe_batch.SetAttribute("OnError", "Continue");
xe_batch.InnerXml = sb_method.ToString();
try
{
//updating the list
XmlNode xn_return = listsObj.UpdateListItems(ConfigurationManager.AppSettings["SaveToSPList"].ToString(), xe_batch);
if (xn_return.InnerText == "0x00000000")
{
successfullySent = true;
}
else
{
successfullySent = false;
}
}
catch
{
successfullySent = false;
}
if (successfullySent)
{
divSuccessfulMessage.Visible = true;
lblSuccessfulMessage.Text = "Report Successfully Saved";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Delete", "<script language='javascript'>$(document).ready(function() {deletePatient(" + id + ");});</script>");
}
else
{
divErrorMessage.Visible = true;
lblErrorMessage.Text = "Failed to Save, Please Try Again";
}
}
}
Thanks in advance.
I'm assuming you're calling the RegisterClientScriptBlock multiple times? In that case, the second parameter of your RegisterClientScriptBlock is the unique key of the script you're trying to inject. Since its always the same, in effect you're basically 'overwriting' each previous script with the latest one.
Try it again, and make sure your key is unique every time you call the RegisterClientScriptBlock (for example, append a counter to it?).
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Delete" + counter.ToString(), "<script language='javascript'>$(document).ready(function() {deletePatient(" + id + ");});</script>");

I wants some data of My Facebook Account but it not allowing me?

I am using http://lite.facebook.com And i want to get some data from my account.
I am using HttpWebRequest for this.
I am able to login to facebook from my credential using web request And I got profile url from home page html.
Now when i am trying to get list of all friends then its kick me out login page.
for login I am using This Code.
string HtmlData = httpHelper.getHtmlfromUrl(new Uri(FacebookUrls.Lite_MainpageUrl));
lstInput = globussRegex.GetInputControlsNameAndValueInPage(HtmlData);
foreach (string str in lstInput)
{
if (str.Contains("lsd"))
{
int FirstPoint = str.IndexOf("name=\"lsd\"");
if (FirstPoint > 0)
{
TempHtmlData = str.Substring(FirstPoint).Replace("name=\"lsd\"","").Replace("value","");
}
int SecondPoint = TempHtmlData.IndexOf("/>");
if (SecondPoint > 0)
{
Value = TempHtmlData.Substring(0, SecondPoint).Replace("=", "").Replace("\\", "").Replace("\"", "").Replace(" ", "");
}
}
}
string LoginData = "form_present=1&lsd=" + Value + "&email=" + UserName + "&password=" + Password + "";
string ResponseData = httpHelper.postFormData(new Uri(FacebookUrls.Lite_LoginUrl), LoginData);
int FirstProfileTag = ResponseData.IndexOf("/p/");
int SecondProfileTag = ResponseData.IndexOf("\">Profile");
if (FirstProfileTag > 0 && SecondProfileTag > 0)
{
string TempProfileUrl = ResponseData.Substring(FirstProfileTag, SecondProfileTag - FirstProfileTag);
string ProfileUrl = FacebookUrls.Lite_ProfileUrl + TempProfileUrl;
GetUserProfileData(ProfileUrl);
}
And For getting Profile Url And FriendList Url Iam doing This
string HtmlData = httpHelper.getHtmlfromUrl(new Uri(ProfileUrl));
string FriendUrl = "http://lite.facebook.com" + "/p/Pankaj-Mishra/1187787295/friends/";
string HtmlData1 = httpHelper.getHtmlfromUrl(new Uri(FriendUrl));
I got perfect result when i tried for ProfileUrl.
but when i tried for frindUrl its logged out how can i solve this problem
Plz help me.
Stop scraping HTML data and use their API

Categories

Resources