checkout.fi payment gateway implement (convert php code to asp.net with C#) - asp.net

I am implementing checkout.fi payment gateway. I got the source code in php and java.I don't have any idea about php. That's why I want to convert Php source code to Asp.net code. Any Help Please
Below link given the sample code of PHP
https://checkoutfinland.github.io/#testing
and other sample java code link on github
https://github.com/AgiSol/checkout-java/
i have made code in asp.net but it is not working. For reference i have taking a Test Data. Below my code. This code run on button click event.
Code here
<pre><code>
protected void Button2_Click(object sender, EventArgs e){
string ver = "0001";
string stamp = DateTime.Now.ToString("yyyyMMddHHmmssfff");
string amount = "1000";
string refer = "2432324";
string message = "hi";
string language = "FI";
string returnurl = "domain.com/return.aspx";
string cancelurl = "domain.com/cancel.aspx";
string reject = "2";
string delaye = "";
string country = "FIN";
string currency = "EUR";
string device = "10"; // 10 = XML
string content = "1";
string type = "0";
string algorithms = "3";
string delivery_date = "20171207";
string firstname = "Tarun";
string family = "Parmar";
string address = "Ääkköstie 5b3\nKulmaravintolan yläkerta";
string postcode = "33100";
string postoffice = "Tampere";
string MERCHANT="375917";
string SECRET_KEY= "SAIPPUAKAUPPIAS";
string macnew = encryptionMD5(ver, stamp, amount, refer, message, language,MERCHANT ,returnurl, cancelurl, reject,delaye, country,currency, device, content, type,algorithms, delivery_date, firstname,family, address, postcode,postoffice, SECRET_KEY).ToUpper();
string email = "support#checkout.fi";
string phone = "0800552010";
string status = "1";
string generatedMac = GetHashSha256(ver,stamp, refer, amount, status, algorithms, SECRET_KEY);
NameValueCollection collections = new NameValueCollection();
collections.Add("VERSION", ver);
collections.Add("STAMP", DateTime.Now.ToString("yyyyMMddHHmmssfff"));
collections.Add("AMOUNT", amount);
collections.Add("REFERENCE", refer);
collections.Add("MESSAGE", message);
collections.Add("LANGUAGE", language);
collections.Add("RETURN", "domain.com/return.aspx");
collections.Add("CANCEL", "domain.com/cancel.aspx");
collections.Add("REJECT", reject);
collections.Add("DELAYED", delaye);
collections.Add("COUNTRY", country);
collections.Add("CURRENCY", currency);
collections.Add("DEVICE", device);
collections.Add("CONTENT", content);
collections.Add("TYPE", type);
collections.Add("ALGORITHM", algorithms);
collections.Add("DELIVERY_DATE", delivery_date);
collections.Add("FIRSTNAME", firstname);
collections.Add("FAMILYNAME", family);
collections.Add("ADDRESS",address);
collections.Add("POSTCODE", postcode);
collections.Add("POSTOFFIC", postoffice);
collections.Add("MAC", macnew);
collections.Add("EMAIL", email);
collections.Add("PHONE", phone);
collections.Add("MERCHANT",MERCHANT);
collections.Add("SECRET_KEY", SECRET_KEY);
string remoteUrl = "https://payment.checkout.fi";
string html = "<html><head>";
html += "</head><body onload='document.forms[0].submit()'>";
html += string.Format("<form name='PostForm' method='POST' action='{0}'>", remoteUrl);
foreach (string key in collections.Keys)
{
html += string.Format("<input name='{0}' type='text' value='{1}'>", key, collections[key]);
}
html += "</form></body></html>";
Response.Clear();
Response.ContentEncoding = Encoding.GetEncoding("ISO-8859-1");
Response.HeaderEncoding = Encoding.GetEncoding("ISO-8859-1");
Response.Charset = "ISO-8859-1";
Response.Write(html);
Response.End();
}
Function For encryptionMD5
public string encryptionMD5(String VERSION, String STAMP, String AMOUNT, String REFERENCEs, String MESSAGE, String LANGUAGE, String merchantId, String RETURN, String CANCEL, String REJECT, String DELAYED, String COUNTRY, String CURRENCY, String DEVICE, String CONTENT, String TYPE, String ALGORITHM, String DELIVERY_DATE, String FIRSTNAME, String FAMILYNAME, String ADDRESS, String POSTCODE, String POSTOFFICE, String PasswordID)
{
string passwords = VERSION + STAMP + AMOUNT + REFERENCEs + MESSAGE + LANGUAGE + merchantId + RETURN + CANCEL + REJECT + DELAYED + COUNTRY + CURRENCY + DEVICE + CONTENT + TYPE + ALGORITHM + DELIVERY_DATE + FIRSTNAME + FAMILYNAME + ADDRESS + POSTCODE + POSTOFFICE + PasswordID;
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] encrypt;
UTF8Encoding encode = new UTF8Encoding();
encrypt = md5.ComputeHash(encode.GetBytes(passwords));
StringBuilder encryptdata = new StringBuilder();
for (int i= 0; i<encrypt.Length; i++) {
encryptdata.Append(encrypt[i].ToString());
}
return encryptdata.ToString();
}
Function For GetHashSha256
<pre><code>
public string GetHashSha256(string VERSION,string STAMP, string REFERENCE,string PAYMENT, string STATUS, string ALGORITHM, string password)
{
string text = VERSION + STAMP + REFERENCE + PAYMENT + STATUS + ALGORITHM + password;
byte[] bytes = Encoding.ASCII.GetBytes(text);
SHA256Managed hashstring = new SHA256Managed();
byte[] hash = hashstring.ComputeHash(bytes);
string hashString = string.Empty;
foreach (byte x in hash)
{
hashString += String.Format("{0:x2}", x);
}
return hashString;
}
This above code give below error
Creating a Payment Transaction failed (-24).
Error in field: MAC
Thanks in Advance if anybody help in solving this problem.

Well, the Finland checkout payment gateway means that your MAC is not hashed correctly. I downloaded the java version from their github and it works perfectly. You are not generating the correct MD5 hash.
Quite a few problems in your code. First of all you must append + sign with each of the strings because they do same in Java. Second, you are assigning algorithms = "3". You should use algorithms = "2" for MD5. Third your encryptionMD5 doesn't returns correct hash.
Below is the correct implementation that I have done for you:
string ver = "0001";
string stamp = "kpjkq1510841290161";
string amount = "1490";
string refer = "12345";
string message = "My custom message";
string language = "FI";
string returnurl = "http://localhost/success";
string cancelurl = "http://localhost/cancel";
string reject = "http://localhost/rejected";
string delaye = "http://localhost/delayed";
string country = "FIN";
string currency = "EUR";
string device = "10"; // 10 = XML
string content = "1";
string type = "0";
string algorithms = "2";
string delivery_date = "20171123";
string firstname = "Tero";
string family = "Testaaja";
string address = "Mystreet 1";
string postcode = "12345";
string postoffice = "Tampere";
string MERCHANT = "375917";
string SECRET_KEY = "SAIPPUAKAUPPIAS";
using (MD5 md5Hash = MD5.Create())
{
string fromValue = String.Join("+", new string[] { ver, stamp, amount, refer, message, language, MERCHANT, returnurl, cancelurl, reject, delaye, country, currency, device, content, type, algorithms, delivery_date, firstname, family, address, postcode, postoffice, SECRET_KEY });
string macnew = GetMd5Hash(md5Hash, fromValue);
}
public string GetMd5Hash(MD5 md5Hash, string input)
{
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
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 the hexadecimal string.
return sBuilder.ToString();
}
Output is c84e068fcab5c4dad93a29dd4c567b7f
Verified from finland checkout java github project.
And one tip is that you should use StringBuilder for appending text instead of concatenating with + sign for improved performance.

Related

how to return the json data

I want to convert string to json
here i want to convert string data object to json
when i inserted the data using web service page see below
and inserted data look like below:
watch window
Code:
public class WebService1 : System.Web.Services.WebService
{
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["cnn"].ConnectionString);
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string InsertData(string fname, string mname, string lname, string emailid, string password, string contactno, string hobby, string address, string countrycodenum)
{
cn.Open();
string data = fname + mname + lname + emailid + password + contactno + hobby + address + countrycodenum;
string insertquery = "insert into tblstudent(fname, mname, lname, emailid, password, contactno,hobby,address,countrycodenum)values(#fname,#mname,#lname,#emailid,#password,#contactno,#hobby,#address,#countrycodenum)";
SqlCommand cmd = new SqlCommand(insertquery, cn);
//cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#fname", fname);
cmd.Parameters.AddWithValue("#mname", mname);
cmd.Parameters.AddWithValue("#lname", lname);
cmd.Parameters.AddWithValue("#emailid", emailid);
cmd.Parameters.AddWithValue("#password", password);
cmd.Parameters.AddWithValue("#contactno", contactno);
cmd.Parameters.AddWithValue("#hobby", hobby);
cmd.Parameters.AddWithValue("#address", address);
cmd.Parameters.AddWithValue("#countrycodenum", countrycodenum);
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
Console.WriteLine("Insert Successfully");
}
else
{
Console.WriteLine("Not Insert Successfully");
}
cn.Close();
return data;
}
}
}
I install the Newtonsoft package
I want to convert string data object to json??
Instead of this line
string data = fname + mname + lname + emailid + password + contactno + hobby + address + countrycodenum;
Do these two steps.
First create an anonymous object using this line of code:
var dataObject = new { fname, mname, lname, emailid, password, contactno, hobby, address, countrycodenum };
In your example the object would look like this:
{ fname = raju, mname = makvana, lname = dinesh, emailid = raju#gmail.com, password = 12345, contactno = 1234567890, hobby = cricket, address = surat, countrycodenum = uzbekistan }
Second, serialize dataObject to JSON string:
string data = JsonConvert.SerializeObject(dataObject);
Don't forget to use Newtonsoft.Json package.
In your example the JSON string would look like this:
{"fname":"raju","mname":"makvana","lname":"dinesh","emailid":"raju#gmail.com","password":"12345","contactno":"1234567890","hobby":"cricket","address":"surat","countrycodenum":"uzbekistan"}
The entire code is below:
public class WebService1 : System.Web.Services.WebService
{
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["cnn"].ConnectionString);
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string InsertData(string fname, string mname, string lname, string emailid, string password, string contactno, string hobby, string address, string countrycodenum)
{
cn.Open();
// *** this is old code ***
// string data = fname + mname + lname + emailid + password + contactno + hobby + address + countrycodenum;
// *** this is new code ***
var dataObject = new { fname, mname, lname, emailid, password, contactno, hobby, address, countrycodenum };
string data = JsonConvert.SerializeObject(dataObject);
string insertquery = "insert into tblstudent(fname, mname, lname, emailid, password, contactno,hobby,address,countrycodenum)values(#fname,#mname,#lname,#emailid,#password,#contactno,#hobby,#address,#countrycodenum)";
SqlCommand cmd = new SqlCommand(insertquery, cn);
//cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#fname", fname);
cmd.Parameters.AddWithValue("#mname", mname);
cmd.Parameters.AddWithValue("#lname", lname);
cmd.Parameters.AddWithValue("#emailid", emailid);
cmd.Parameters.AddWithValue("#password", password);
cmd.Parameters.AddWithValue("#contactno", contactno);
cmd.Parameters.AddWithValue("#hobby", hobby);
cmd.Parameters.AddWithValue("#address", address);
cmd.Parameters.AddWithValue("#countrycodenum", countrycodenum);
int i = cmd.ExecuteNonQuery();
if (i > 0)
{
Console.WriteLine("Insert Successfully");
}
else
{
Console.WriteLine("Not Insert Successfully");
}
cn.Close();
return data;
}
}
so you can use from newtonsoft.json library and just define your class and it convert to your class
dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject(serviceResult);
foreach (var item in obj1.data)
{
//convert obj1 to your class
}

Ruby OpenSSL::Cipher::CipherError (key not set)

I am trying to port an existing .net encryption code to ruby. But stuck with the key not set error.
Bellow is the .net code to encrypt a string.
private static string Encrypt(string strToEncrypt, string saltValue, string password)
{
using (var csp = new AesCryptoServiceProvider())
{
ICryptoTransform e = GetCryptoTransform(csp, true, saltValue, password);
byte[] inputBuffer = Encoding.UTF8.GetBytes(strToEncrypt);
byte[] output = e.TransformFinalBlock(inputBuffer, 0, inputBuffer.Length);
string encrypted = Convert.ToBase64String(output);
return encrypted;
}
}
private static ICryptoTransform GetCryptoTransform(AesCryptoServiceProvider csp, bool encrypting, string saltValue, string password)
{
csp.Mode = CipherMode.CBC;
csp.Padding = PaddingMode.PKCS7;
var passWord = password;
var salt = saltValue;
//a random Init. Vector. just for testing
String iv = "e675f725e675f123";
var spec = new Rfc2898DeriveBytes(Encoding.UTF8.GetBytes(passWord), Encoding.UTF8.GetBytes(salt), 1000);
byte[] key = spec.GetBytes(16);
csp.IV = Encoding.UTF8.GetBytes(iv);
csp.Key = key;
if (encrypting)
{
return csp.CreateEncryptor();
}
return csp.CreateDecryptor();
}
I have used Ruby's OpenSSL::PKCS5 library to generate key and OpenSSL::Cipher to encrypt using AES algorithm like bellow.
def aes_encrypt(input_string)
cipher = OpenSSL::Cipher.new('AES-128-CBC')
cipher.encrypt
key = encryption_key
iv = cipher.random_iv
cipher.update(input_string) + cipher.final
end
def encryption_key
OpenSSL::PKCS5.pbkdf2_hmac_sha1(PASSWORD, SALT, 1000, 16)
end
Can anyone let know where I am missing? (Padding ?)

asp.net C# webform show report without reportviewer

currently i want to generate the report without showing in reportviewer. I search for the solution online but i only can find the MVC approach. I cant convert it to normal webform behavior.
public ActionResult Report(string id)
{
LocalReport lr = new LocalReport();
string path = Path.Combine(Server.MapPath("~/Report"), "ReportStateArea.rdlc");
if (System.IO.File.Exists(path))
{
lr.ReportPath = path;
}
else
{
return View("Index");
}
List<StateArea> cm = new List<StateArea>();
using (PopulationEntities dc = new PopulationEntities())
{
cm = dc.StateAreas.ToList();
}
ReportDataSource rd = new ReportDataSource("MyDataset", cm);
lr.DataSources.Add(rd);
string reportType = id;
string mimeType;
string encoding;
string fileNameExtension;
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>" + id + "</OutputFormat>" +
" <PageWidth>8.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.5in</MarginTop>" +
" <MarginLeft>1in</MarginLeft>" +
" <MarginRight>1in</MarginRight>" +
" <MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
renderedBytes = lr.Render(
reportType,
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
return File(renderedBytes, mimeType);
}
enter code here
Here is the sample of code that can allow user to generate the report in different format such as PDF, excel, image. ( http://www.dotnetawesome.com/2013/09/microsoft-report-in-mvc-4.html ).
Anyone can help or provide me a website which have a simple tutorial of that by using the SQL select statement instead of LINQ ?
As far as returning the report from a WebForms page, what you have above is actually pretty close. You want to return the renderedBytes array through the Response object of your current Page context like:
protected void ReportPrint_Click(object sender, EventArgs e)
{
string id = "PDF"; // get this from another control on your page
LocalReport lr = new LocalReport();
string path = Path.Combine(Server.MapPath("~/Report"), "ReportStateArea.rdlc");
if (System.IO.File.Exists(path))
{
lr.ReportPath = path;
}
else
{
// handle error condition
}
List<StateArea> cm = new List<StateArea>();
using (PopulationEntities dc = new PopulationEntities())
{
cm = dc.StateAreas.ToList();
}
ReportDataSource rd = new ReportDataSource("MyDataset", cm);
lr.DataSources.Add(rd);
string reportType = id;
string mimeType;
string encoding;
string fileNameExtension;
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>" + id + "</OutputFormat>" +
" <PageWidth>8.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.5in</MarginTop>" +
" <MarginLeft>1in</MarginLeft>" +
" <MarginRight>1in</MarginRight>" +
" <MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
renderedBytes = lr.Render(
reportType,
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
Response.Clear(); // we're going to override the default page response
Response.ContentType = mimeType;
Response.AddHeader("content-disposition", "attachment; filename=report." + fileNameExtension);
Response.BinaryWrite(renderedBytes);
Response.End();
}
This will replace the normal page response with your report content.
As far as SQL vs Linq, the DataSource object that ReportViewer uses is the old-style System.Data.DataTable so just look for information on populating a DataTable from SQL.

Converting issue Byte to Byte

i never work with Bytes before i have a getting error here in may code please have a look
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
SqlDataReader dr = ExecuteReader(Globals.con, CommandType.Text,
"select FileName,MediaData,Extension from media where Id=" + ID);
string FileName="";
Byte[] MediaData= null;
string Extension = "";
while (dr.Read())
{
FileName = dr["FileName"].ToString();
MediaData = Convert.ToByte(dr["MediaData"].ToString()); error is here
Extension = dr["Extension"].ToString();
}
dr.Close();
string filename = (String)FileName;
byte[] fileToDownload = (byte[])MediaData;
String fileExtension = (String)Extension;
in gridview i use this code below it working i need manual date
not like code below
string filename = (String)reader.GetValue(1);
byte[] fileToDownload = (byte[])reader.GetValue(2);
String fileExtension = (String)reader.GetValue(3);
please help me out in it
Convert.ToByte returns a single byte, not an array.
You are also using ToString which can completely convert the binary data into a representation that you can't use:
MediaData = Convert.ToByte(dr["MediaData"].ToString())
Should be:
MediaData = (byte[])dr.Items["MediaData"];

Object reference not set to an instance of an object

I am facing an issue while inserting some items into database in asp.net web service application.
Here is my code ..
public void DoRequestLog(HttpRequest request)
{
string UserAgent = request.Headers["User-Agent"];
string Date = "4/14/2011";//request.Headers["Date"];
string HostIP = request.Headers["Host"];
string URL = request.Headers["Referer"];
string MethodName = request.HttpMethod;
string VersionNo = "";
string IMEINo = "";
string dbString = Configuration.GetDBConnectionString();
SqlConnection DardSqlConnection = new SqlConnection(dbString);
DardSqlConnection.Open();
SqlCommand log = DardSqlConnection.CreateCommand();
log.CommandText = "insert into ConnectionLog values('"+UserAgent+"','"+Date+"','"+HostIP+"','"+URL+"','"+MethodName+"','"+VersionNo+"','"+IMEINo+"');";
log.ExecuteNonQuery();
}
Please Help
Since I am new to .net environment.
Try this:
public void DoRequestLog(HttpRequest request)
{
// We don’t need to log anything if there is no HTTP request.
if (request == null)
return;
string UserAgent = request.Headers["User-Agent"];
string Date = "4/14/2011";//request.Headers["Date"];
...

Resources