Can anybody explain how to integrate third party payment migs (MasterCard Virtual Payment Client) in C#?
Anyone who has done a similar project or has any clue as to what am missing here, can be of great help to me. In case of any question, I shall clarify in details. Thank you.
try
{
//Define Variables
string MerchantId = "00000047";
string Amount = txtAmountUSD.Text.Trim();
long PhoneNumber=long.Parse( txtPhoneNumber.Text.Trim().ToString());
string AccessCode = "4EC13697";
string SECURE_SECRET = "A1A3999770F5893719AE0076C7F18834";
string ReturnUrl = "http://localhost:2035/Core/frmMoneyTransfer.aspx";
string DestinationUrl = "https://migs.mastercard.com.au/vpcpay?";
string MerchantTransactionRef = Amount + DateTime.Now;
string Command = "Pay";
var HashData = SECURE_SECRET;
string postData = "vpc_Merchant=" + MerchantId;
postData += ("&vpc_Amount=" + Amount);
postData += ("&vpc_AccessCode=" + AccessCode);
postData += ("&vpc_Command=" + Command);
postData += ("&vpc_MerchTxnRef=" + MerchantTransactionRef);
postData += ("&vpc_ReturnURL=" + ReturnUrl);
postData += ("&vpc_SecureHashType=" + "SHA256");
postData += ("&vpc_OrderInfo=" + PhoneNumber );
postData += ("&vpc_Version=" + "1.0");
postData+=("&vpc_SecureHash="+SECURE_SECRET );
HttpWebRequest request1 = (HttpWebRequest)WebRequest.Create(DestinationUrl);
request1.Method = "POST";
request1.ContentType = "application/x-www-form-urlencoded";
request1.AllowAutoRedirect = true;
request1.ProtocolVersion = HttpVersion.Version11;
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(postData);
request1.ContentLength = bytes.Length;
Stream requestStream = request1.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
WebResponse response = request1.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
var result = reader.ReadToEnd();
Response.Redirect(request1.Address.ToString(), false );
stream.Dispose();
reader.Dispose();
}
catch (Exception Ex)
{
lblInfo.Text= Ex.Message.ToString();
}
Related
I am trying to create credit card payment page.
I am posting the form in code behind (C#) and successfully get the verification sms from bank.
But it does not redirect to bank sms verification page so there is no where to enter verification code.
So what should i do?
Here is my code under the Pay button:
String shopCode = "SHOPCODE";
String purchaseAmount = "ORDER PRICE";
String currency = "CURRENCY";
String orderId = "ORDERID";
String okUrl = "REDIRECT PAGE AFTER SMS VERIFICATION COMPLETED SUCCESSFULLY";
String failUrl = "REDIRECT PAGE IF SMS VERIFICATION FAILS";
String rnd = DateTime.Now.ToString();
String installmentCount = "3";
String txnType = "txnType";
String merchantPass = "merchantpass";
String str = shopCode + orderId + purchaseAmount + okUrl + failUrl + txnType + installmentCount + rnd + merchantPass;
System.Security.Cryptography.SHA1 sha = new System.Security.Cryptography.SHA1CryptoServiceProvider();
byte[] bytes = System.Text.Encoding.GetEncoding("ISO-8859-9").GetBytes(str);
byte[] hashingbytes = sha.ComputeHash(bytes);
String hash = Convert.ToBase64String(hashingbytes);
String cardnumber = "CREDIT CARD NUMBER";
String expiry = "EXPIRY DATE";
String CVCCVV = "CVCNUMBER";
String securetype = "3DPay";
String lang = "language";
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "Pan=" + cardnumber;
postData += ("&Expiry=" + expiry);
postData += ("&Cvv2=" + CVCCVV);
postData += ("&ShopCode=" + shopCode);
postData += ("&PurchAmount=" + purchaseAmount);
postData += ("&Currency=" + currency);
postData += ("&OrderId=" + orderId);
postData += ("&OkUrl=" + okUrl);
postData += ("&FailUrl=" + failUrl);
postData += ("&Rnd=" + rnd);
postData += ("&Hash=" + hash);
postData += ("&TxnType=" + txnType);
postData += ("&InstallmentCount=" + installmentCount);
postData += ("&SecureType=" + securetype);
postData += ("&Lang=" + lang);
byte[] data = encoding.GetBytes(postData);
HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create("POSURL");
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream = myRequest.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
EDIT:
It works fine if i do it in client (html) side, but i want to do it in server side.
we need json information from the bank
try
{
HttpClient clients = new HttpClient();
clients.Timeout = TimeSpan.FromSeconds(2);
HttpResponseMessage _response = await clients.GetAsync("banksmspage");
_response.EnsureSuccessStatusCode();
string responseBody = await _response.Content.ReadAsStringAsync();
dynamic json = JObject.Parse(responseBody);
string smscode = json.jsontitle.smscode;
if (smscode != null)
{
if (smscode == UsersmsEnterString)
{
Response.Redirect("BankpageURL");
}
else
{
Response.Redirect("ErrorURL");
}
}
}
catch {}
I have following code which give "Error:MissingRegistration" response from GCM server.
public void SendPushNotification()
{
string stringregIds = null;
List<string> regIDs = _db.Directories.Where(i => i.GCM != null && i.GCM != "").Select(i => i.GCM).ToList();
//Here I add the registrationID that I used in Method #1 to regIDs
stringregIds = string.Join("\",\"", regIDs);
//To Join the values (if ever there are more than 1) with quotes and commas for the Json format below
try
{
string GoogleAppID = "AIzaSyA2Wkdnp__rBokCmyloMFfENchJQb59tX8";
var SENDER_ID = "925760665756";
var value = "Hello";
WebRequest tRequest;
tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
tRequest.Method = "post";
Request.ContentType = "application/json";
tRequest.Headers.Add(string.Format("Authorization: key={0}", GoogleAppID));
tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
string postData = "{\"collapse_key\":\"score_update\",\"time_to_live\":108,\"delay_while_idle\":true,\"data\": { \"message\" : " + "\"" + value + "\",\"time\": " + "\"" + System.DateTime.Now.ToString() + "\"},\"registration_ids\":[\"" + stringregIds + "\"]}";
Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
tRequest.ContentLength = byteArray.Length;
Stream dataStream = tRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse tResponse = tRequest.GetResponse();
dataStream = tResponse.GetResponseStream();
StreamReader tReader = new StreamReader(dataStream);
string sResponseFromServer = tReader.ReadToEnd();
TempData["msg1"] = "<script>alert('" + sResponseFromServer + "');</script>";
HttpWebResponse httpResponse = (HttpWebResponse)tResponse;
string statusCode = httpResponse.StatusCode.ToString();
tReader.Close();
dataStream.Close();
tResponse.Close();
}
catch (Exception ex)
{
}
}
But exact string returned by 'postData' posted by Postman or Fiddler gives positive response and notification arrived at device.
What I'm missing in my code please help me.
The postData returns this value which successfully posted by Postman And Fiddler
{"collapse_key":"score_update","time_to_live":108,"delay_while_idle":true,"data": { "message" : "Hello","time": "5/13/2016 5:50:59 PM"},"registration_ids":["cXMf6hkYIrw:APA91bGr-8y2Gy-qzNJ3zjrlf8t-4m9uDib9P0j8GW87bH5jq891-x_7P0qqItzlc_HXh11Arg76lCOcjXPrU9LAgtYLwllH2ySxA0ADSfiz3qPolajjvI3d3zE6Rh77dwRqXn3NnbAm"]}
The problem in your code is in ContentType
Instead of using this:-
Request.ContentType = "application/json";
Use
tRequest.ContentType = "application/json";
It will work
Try This:-
private string SendGCMNotification()
{
try
{
string message = "some test message";
//string tickerText = "example test GCM";
string contentTitle = "content title GCM";
string registration_id = "cXMf6hkYIrw:APA91bGr-8y2Gy-qzNJ3zjrlf8t-4m9uDib9P0j8GW87bH5jq891-x_7P0qqItzlc_HXh11Arg76lCOcjXPrU9LAgtYLwllH2ySxA0ADSfiz3qPolajjvI3d3zE6Rh77dwRqXn3NnbAm";
string postData =
"{ \"registration_ids\": [ \"" + registration_id + "\" ], " +
"\"data\": {\"contentTitle\":\"" + contentTitle + "\", " +
"\"message\": \"" + message + "\"}}";
string GoogleAppID = "AIzaSyA2Wkdnp__rBokCmyloMFfENchJQb59tX8";
WebRequest wRequest;
wRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
wRequest.Method = "POST";
wRequest.ContentType = " application/json;charset=UTF-8";
wRequest.Headers.Add(string.Format("Authorization: key={0}", GoogleAppID));
var bytes = Encoding.UTF8.GetBytes(postData);
wRequest.ContentLength = bytes.Length;
var stream = wRequest.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
stream.Close();
var wResponse = wRequest.GetResponse();
stream = wResponse.GetResponseStream();
var reader = new StreamReader(stream);
var response = reader.ReadToEnd();
var httpResponse = (HttpWebResponse)wResponse;
var status = httpResponse.StatusCode.ToString();
reader.Close();
stream.Close();
wResponse.Close();
//TODO check status
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return "sent";
}
here is the picture of it .. look here also /.. http://prntscr.com/5wadok
string fbid = stTextBox1.Text;
string ukey = stTextBox2.Text;
string jumlah = "4";
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "fbid=" + fbid + "&ukey=" + ukey + "&jumlah=" + jumlah; ;
byte[] data = encoding.GetBytes(postData);
WebRequest request = WebRequest.Create("http://dcvn-full.ga/test/dcgems.php");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
Stream stream = request.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
WebResponse response = request.GetResponse();
stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
//MessageBox.Show(sr.ReadToEnd());
stLabel4.Text = (sr.ReadLine());
sr.Close();
stream.Close();
I need to read the line21to25 and show it in the stlabel.5 with this command or any other , can u help me??
I modified your code as follows. Hopefully it will solve your problem.
string fbid = stTextBox1.Text;
string ukey = stTextBox2.Text;
string jumlah = "4";
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "fbid=" + fbid + "&ukey=" + ukey + "&jumlah=" + jumlah; ;
byte[] data = encoding.GetBytes(postData);
WebRequest request = WebRequest.Create("http://dcvn-full.ga/test/dcgems.php");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
WebResponse response = request.GetResponse();
stream = response.GetResponseStream();
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(stream))
{
int count=1;
while(sr.EndOfStream)
{
string line = sr.ReadLine();
if(count>=21 && count<=25)
{
sb.AppendLine(line);
}
count++;
if (count > 25)
break;
}
stLabel4.Text = (sb.ToString());
}
I'm trying to figure out how to post a new task to a user in asana, but I keep getting the 400 error code. Can anyone tell me what I am doing wrong.
This is what I have so far:
string apiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string ID = "xxxxxxxxxxxxx";
string url = #"https://app.asana.com/api/1.0/tasks";
Data dat = new Data();
dat.workspace = ID;
dat.name = "Buy eggs";
dat.notes = "Testing";
string json = JsonConvert.SerializeObject(dat);
string data ="\"data\": " + json;
byte[] bytes = Encoding.UTF8.GetBytes(data);
var req = (HttpWebRequest)WebRequest.Create(url);
Console.WriteLine(bytes.ToString());
req.Method = WebRequestMethods.Http.Post;
req.ContentLength = bytes.Length;
req.ContentType = "application/json";
var authInfo = apiKey + ":";
var encodedAuthInfo = Convert.ToBase64String(
Encoding.Default.GetBytes(authInfo));
req.Headers.Add("Authorization", "Basic " + encodedAuthInfo);
req.ContentLength = bytes.Length;
Stream reqStream = req.GetRequestStream();
reqStream.Write(bytes, 0, bytes.Length);
reqStream.Close();
try
{
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
string res = new StreamReader(response.GetResponseStream()).ReadToEnd();
Console.WriteLine(res);
Console.ReadLine();
}
catch (WebException ex)
{
HttpWebResponse response = ((HttpWebResponse)ex.Response);
string e = url + " caused a " + (int)response.StatusCode + " error.\n" + response.StatusDescription;
Console.WriteLine(e);
Console.ReadLine();
}
I put the serial converter, did i do it wrong?
As the first comment points out, you need to serialize the data properly. The final body posted should look something like:
{ "data": { "name": "My Example Task", ... }}
(Except of course with the ... replaced with more fields.)
I have researched a long and found below code useful and working. I can successfully post Task to Asana through my application. I have used Json serializer for dot net. Thanks to Newtonsoft.Json.
string json = null;
byte[] bytes = null;
string url = "https://app.asana.com/api/1.0/tasks";
HttpWebRequest req = default(HttpWebRequest);
Stream reqStream = default(Stream);
string authInfo = null;
Task TaskData = new Task();
try
{
authInfo = apiKey + Convert.ToString(":");
TaskData.workspace = WorkspaceId;
TaskData.name = TaskName;
TaskData.notes = TaskNotes;
json = JsonConvert.SerializeObject(TaskData);
json = json.Insert((json.Length - 1), ",\"projects\":[" + ProjectId + "]");
json = Convert.ToString("{ \"data\":") + json + "}";
bytes = Encoding.UTF8.GetBytes(json);
req = (HttpWebRequest)WebRequest.Create(url);
req.Method = WebRequestMethods.Http.Post;
req.ContentType = "application/json";
req.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(authInfo)));
req.ContentLength = bytes.Length;
reqStream = req.GetRequestStream();
reqStream.Write(bytes, 0, bytes.Length);
reqStream.Close();
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
string res = new StreamReader(response.GetResponseStream()).ReadToEnd();
Console.WriteLine(res);
Console.ReadLine();
string finalString = res.Remove(0, 8);
finalString = finalString.Remove((finalString.Length - 1));
AsanaObjectId newtask = JsonConvert.DeserializeObject<AsanaObjectId>(finalString);
return newtask;
}
catch (WebException ex)
{
HttpWebResponse response = (HttpWebResponse)ex.Response;
string resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
MessageBox.Show(resp);
System.Environment.Exit(0);
}
The problem with this code is that the file, once it is uploaded, is not the correct format. I'm trying to upload a .zip file.
public string HttpPost(string uri, string parameter)
{
WebRequest webRequest = WebRequest.Create(uri);
NetworkCredential credentials = new NetworkCredential("username", "password");
webRequest.Credentials = credentials;
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(parameter);
Stream os = null;
try
{ // send the Post
webRequest.ContentLength = bytes.Length; //Count bytes to send
os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length); //Send it
}
catch (WebException ex)
{
MessageBox.Show(ex.Message, "HttpPost: Request error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (os != null)
{
os.Close();
}
}
try
{ // get the response
WebResponse webResponse = webRequest.GetResponse();
if (webResponse == null)
{ return null; }
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
return sr.ReadToEnd().Trim();
}
catch (WebException ex)
{
MessageBox.Show(ex.Message, "HttpPost: Response error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return null;
}
This example how to upload file in MyBucket
private const string KeyId = "Your KeyId";
private const string AccessKey = "Your AccessKey";
private const string S3Url = "https://s3.amazonaws.com/";
private static void UploadFile()
{
var fileData = File.ReadAllBytes(#"C:\123.zip");
string timeStamp = string.Format("{0:r}", DateTime.UtcNow);
string stringToConvert = "PUT\n" + //Http verb
"\n" + //content-md5
"application/octet-stream\n" + //content-type
"\n" + //date
"x-amz-acl:public-read"+"\n" + //date
"x-amz-date:" + timeStamp + "\n" + //optionall
"/MyBucket/123.zip"; //resource
var ae = new UTF8Encoding();
var signature = new HMACSHA1 {Key = ae.GetBytes(AccessKey)};
var bytes = ae.GetBytes(stringToConvert);
var moreBytes = signature.ComputeHash(bytes);
var encodedCanonical = Convert.ToBase64String(moreBytes);
var url = "https://MyBucket.s3.amazonaws.com/123.zip";
var request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "PUT";
request.Headers["x-amz-date"] = timeStamp;
request.Headers["x-amz-acl"] = "public-read";
request.ContentType = "application/octet-stream";
request.ContentLength = fileData.Length;
request.Headers["Authorization"] = "AWS " + KeyId + ":" + encodedCanonical;
var requestStream = request.GetRequestStream();
requestStream.Write(fileData, 0, fileData.Length);
requestStream.Close();
using (var response = request.GetResponse() as HttpWebResponse)
{
var reader = new StreamReader(response.GetResponseStream());
var data = reader.ReadToEnd();
}
}
Take a look on Amazon S3 REST API