The problem I am facing is that, payfort API should return me some json. But instead i get some html that has some hidden fields. and i see no error written inside there.
Here is my code
string access_code = string.Empty,
amount = string.Empty,
currency = string.Empty,
customer_email = string.Empty,
merchant_reference = string.Empty,
order_description = string.Empty,
language = string.Empty,
merchant_identifier = string.Empty,
signature = string.Empty,
command = string.Empty;
access_code = "X78979879h8h8h8";
amount = "1000";
command = "AUTHORIZATION";
currency = "AED";
customer_email = "zetawars#hotmail.com";
language = "en";
merchant_identifier = "RaskdQuCc";
merchant_reference = "ASASASASASADSS";
order_description = "Some order details";
signature = "";
string signature_string = "PASSaccess_code="+access_code+"amount="+amount+"command="+command+"currency="+currency+"customer_email"+customer_email+"language"+language+"merchant_identifier"+merchant_identifier+"merchant_reference"+merchant_reference+"order_description"+order_description+"PASS";
signature = getHashSha256(signature_string);
string url = "https://sbcheckout.payfort.com/FortAPI/paymentPage";
string param = "access_code" + access_code + "&amount=" + amount + "¤cy=" + currency +
"&customer_email=" + customer_email + "&merchant_reference=" + merchant_reference +
"&order_description=" + order_description + "&language=" + language + "merchant_identifier="
+ merchant_identifier + "&signature=" + signature + "&command=" + command;
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/json";
//wc.Headers.Add("Content-Type", "application/json");
string HtmlResult = wc.UploadString(url, param);
}
Try adding values for below header
wc.Headers[HttpRequestHeader.Authorization]
wc.Headers[HttpRequestHeader.TenantId]
wc.Headers[HttpRequestHeader.Client-Type]
wc.Headers[HttpRequestHeader.Protocol]
Works for me!!
First Encode the response
string responseString = Encoding.UTF8.GetString(response);
Use HtmlDocument (HtmlAgilityPack)
var html = new HtmlDocument();
var tokenValue = "";
html.LoadHtml(responseString);
After Loading This into html you can query fields and values.
var tokenFormIdElement =
html.DocumentNode.SelectSingleNode("//input[#name='token']");
tokenValue = tokenFormIdElement.GetAttributeValue("value", "");
Related
will appreciate any Help on this one.
I am trying to replace text in an email template using Mailkit. The issue is that in Mailkit there is at least a text part and and Html part.
I can get then set the text part using code such as:
var textPart = message.BodyParts.OfType<TextPart>().FirstOrDefault();
I can get the htmlbody using
var htmlPart = message.htmlBody
but once I modify it I do not know how to set the htmlpart to the message's htmlBody.
My code so far:
FileStream sr = new FileStream(fileLocation + "\\" + fileName, FileMode.Open, FileAccess.Read);
message = MimeMessage.Load(sr);
sr.Close();
//Get the text Part
var textPart = message.BodyParts.OfType<TextPart>().FirstOrDefault();
//Get the HtmlBody
var htmlPart = message.HtmlBody;
string regexPattern;
string regexReplacement;
Regex regexText;
foreach (var replaceSet in replaceArray)
{
regexPattern = "#" + replaceSet["Key"].ToString() + "#";
regexReplacement = (string)replaceSet["Value"].ToString();
//bool test = Regex.IsMatch(docText, regexPattern);
if (regexReplacement != "")
{
regexText = new Regex(regexPattern);
textPart.Text = regexText.Replace(textPart.Text, regexReplacement);
//Set, modify the text part
htmlPart = regexText.Replace(htmlPart, regexReplacement);
}
}
try
{
message.WriteTo(fileLocation + "\\output\\" + fileName);
}
catch (Exception Ex)
{
result = Ex.Message;
return BadRequest(result);
}```
Something like this will probably work:
// Get the text Part
var textPart = message.BodyParts.OfType<TextPart>().FirstOrDefault(x => x.IsPlain);
var htmlPart = message.BodyParts.OfType<TextPart>().FirstOrDefault(x => x.IsHtml);
string regexPattern;
string regexReplacement;
Regex regexText;
foreach (var replaceSet in replaceArray)
{
regexPattern = "#" + replaceSet["Key"].ToString() + "#";
regexReplacement = (string)replaceSet["Value"].ToString();
//bool test = Regex.IsMatch(docText, regexPattern);
if (regexReplacement != "")
{
regexText = new Regex(regexPattern);
textPart.Text = regexText.Replace(textPart.Text, regexReplacement);
//Set, modify the text part
htmlPart.Text = regexText.Replace(htmlPart.Text, regexReplacement);
}
}
I'm using an example for setting up HMAC authentication for a Web API project. The original example source code/project is available here:
http://bitoftech.net/2014/12/15/secure-asp-net-web-api-using-api-key-authentication-hmac-authentication/
I'm trying to get Postman to construct and send a GET request in it's pre-request script. However the request always fails with a 401 and I can't figure out why.
Postman pre-request script:
var AppId = "4d53bce03ec34c0a911182d4c228ee6c";
var APIKey = "A93reRTUJHsCuQSHR+L3GxqOJyDmQpCgps102ciuabc=";
var requestURI = "http%3a%2f%2flocalhost%3a55441%2fapi%2fv1%2fdata";
var requestMethod = "GET";
var requestTimeStamp = "{{$timestamp}}";
var nonce = "1";
var requestContentBase64String = "";
var signatureRawData = AppId + requestMethod + requestURI + requestTimeStamp + nonce + requestContentBase64String; //check
var signature = CryptoJS.enc.Utf8.parse(signatureRawData);
var secretByteArray = CryptoJS.enc.Base64.parse(APIKey);
var signatureBytes = CryptoJS.HmacSHA256(signature,secretByteArray)
var requestSignatureBase64String = CryptoJS.enc.Base64.stringify(signatureBytes);
postman.setGlobalVariable("key", "amx " + AppId + ":" + requestSignatureBase64String + ":" + nonce + ":" + requestTimeStamp);
This is the code I'm using in my Pre-Script. It works for any query GET, PUT, POST, DELETE.
You need to change the AppId & the APIKey values and on the last line adjust the name of the environment variable "hmacKey" with yours.
function interpolate (value) {
const {Property} = require('postman-collection');
return Property.replaceSubstitutions(value, pm.variables.toObject());
}
var uuid = require('uuid');
var moment = require("moment")
var hmacPrefix = "hmac";
var AppId = "4d53bce03ec34c0a911182d4c228ee6c";
var APIKey = "A93reRTUJHsCuQSHR+L3GxqOJyDmQpCgps102ciuabc=";
var requestURI = encodeURIComponent(pm.environment.values.substitute(pm.request.url, null, false).toString().toLowerCase());
var requestMethod = pm.request.method;
var requestTimeStamp = moment(new Date().toUTCString()).valueOf() / 1000;
var nonce = uuid.v4();
var requestContentBase64String = "";
var bodyString = interpolate(pm.request.body.toString());
if (bodyString) {
var md5 = CryptoJS.MD5(bodyString);
requestContentBase64String = CryptoJS.enc.Base64.stringify(md5);
}
var signatureRawData = AppId + requestMethod + requestURI + requestTimeStamp + nonce + requestContentBase64String; //check
var signature = CryptoJS.enc.Utf8.parse(signatureRawData);
var secretByteArray = CryptoJS.enc.Base64.parse(APIKey);
var signatureBytes = CryptoJS.HmacSHA256(signature,secretByteArray);
var requestSignatureBase64String = CryptoJS.enc.Base64.stringify(signatureBytes);
var hmacKey = hmacPrefix + " " + AppId + ":" + requestSignatureBase64String + ":" + nonce + ":" + requestTimeStamp;
postman.setEnvironmentVariable("hmacKey", hmacKey);
After a few days of testing I figured out the problem. It was actually to do with the variable placeholders provided by Postman of all things. In testing the placeholder {{$timestamp}} at face value was passing a valid value. When I stripped the signature back to start with just a single segment I was getting authenticated successfully. Until of course I put the timestamp placeholder back in.
When I swapped out the placeholder for the actual value passed in the header it worked fine. I can only conclude that there must be some extra character I can't see. Perhaps on the Postman side when it creates the signature. The problem extends to other placeholders such as {{$guid}}.
If you are having trouble with the script provided by Florian SANTI and you are using Postman v8.0 or higher. You'll need to make sure that the empty string is set by the variable requestContentBase64String is set properly by correctly inspecting the request body.
This is how I solved the issue.
var uuid = require('uuid');
var moment = require("moment")
var AppId = "4d53bce03ec34c0a911182d4c228ee6c";
var APIKey = "A93reRTUJHsCuQSHR+L3GxqOJyDmQpCgps102ciuabc=";
var requestURI = encodeURIComponent(pm.environment.values.substitute(pm.request.url, null, false).toString()).toLowerCase();
var requestMethod = pm.request.method;
var requestTimeStamp = moment(new Date().toUTCString()).valueOf() / 1000;
var nonce = uuid.v4();
var hasBody = (pm.request.body !== null);
if (hasBody) {
hasBody = (!pm.request.body.isEmpty);
}
var requestContentBase64String = "";
if (hasBody) {
var md5 = CryptoJS.MD5(JSON.stringify(postBody));
requestContentBase64String = CryptoJS.enc.Base64.stringify(md5);
}
var signatureRawData = AppId + requestMethod + requestURI + requestTimeStamp + nonce + requestContentBase64String; //check
var signature = CryptoJS.enc.Utf8.parse(signatureRawData);
var secretByteArray = CryptoJS.enc.Base64.parse(APIKey);
var signatureBytes = CryptoJS.HmacSHA256(signature,secretByteArray);
var requestSignatureBase64String = CryptoJS.enc.Base64.stringify(signatureBytes);
var hmacKey = "amx " + AppId + ":" + requestSignatureBase64String + ":" + nonce + ":" + requestTimeStamp;
postman.setEnvironmentVariable("hmacKey", hmacKey );
I've been wrestling with this for a while now and can't seem to find a solution. The closest I've come is PHP code for Oauth-1 by Joe Chung (https://github.com/joechung/oauth_yahoo), but I can't get my head wrapped around it.
I'm using Asp.Net, and this code is in the ContactController. I have no trouble Getting contacts from Yahoo. The problem is Adding a contact to a user's Yahoo address book. The program proceeds through the Yahoo login process, and there are no errors. But the contact is not saved. I hope someone can take a look at this and tell me what I'm missing.
Thanks.
private string AddYahooContact(string responseFromServer, string contactIdForYahoo)
{
// Some of this from http://www.yogihosting.com/implementing-yahoo-contact-reader-in-asp-net-and-csharp/
responseFromServer = responseFromServer.Substring(1, responseFromServer.Length - 2);
string accessToken = "", xoauthYahooGuid = "", refreshToken = "";
string[] splitByComma = responseFromServer.Split(',');
foreach (string value in splitByComma)
{
if (value.Contains("access_token"))
{
string[] accessTokenSplitByColon = value.Split(':');
accessToken = accessTokenSplitByColon[1].Replace('"'.ToString(), "");
}
else if (value.Contains("xoauth_yahoo_guid"))
{
string[] xoauthYahooGuidSplitByColon = value.Split(':');
xoauthYahooGuid = xoauthYahooGuidSplitByColon[1].Replace('"'.ToString(), "");
}
else if (value.Contains("refresh_token"))
{
string[] refreshTokenSplitByColon = value.Split(':');
refreshToken = refreshTokenSplitByColon[1].Replace('"'.ToString(), "");
}
}
// How to build contactUrl from https://developer.yahoo.com/social/rest_api_guide/contacts-resource.html#contacts-xml_request_put
// This is Yahoo's address to add a contact
string contactUrl = "https://social.yahooapis.com/v1/user/" + xoauthYahooGuid + "/contacts";
// Much of this from https://developer.yahoo.com/dotnet/howto-rest_cs.html
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(contactUrl);
webRequest.Method = "POST";
webRequest.Headers["Authorization"] = "Bearer " + accessToken;
webRequest.ContentType = "application/x-www-form-urlencoded"; // Tried "application/x-www-form-urlencoded & application/xml" & "text/xml".
// Create the data we want to send
string yahooContact = BuildYahooContact(contactIdForYahoo);
byte[] byteData = UTF8Encoding.UTF8.GetBytes(yahooContact);
webRequest.ContentLength = byteData.Length;
using (Stream postStream = webRequest.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
responseFromServer = "";
try
{
using (HttpWebResponse response = webRequest.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
responseFromServer = reader.ReadToEnd();
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return yahooContact;
}
private string BuildYahooContact(string contactIdForYahoo)
{
Guid contactId = Guid.Parse(contactIdForYahoo);
Models.Contact contact = GetContactForId(contactId); // And find the contact
string firstName = "";
string lastName = "";
if (contact.FullName != null)
{
int index = contact.FullName.IndexOf(" ");
if (index > 0)
{
firstName = contact.FullName.Substring(0, index);
lastName = (contact.FullName.Substring(index + 1));
}
else
{
lastName = contact.FullName;
}
}
StringBuilder data = new StringBuilder();
data.Append("<contact>");
data.Append("<fields><type>name</type><value>");
data.Append("<givenName>" + firstName + "</givenName><middleName/>");
data.Append("<familyName>" + lastName + "</familyName>");
data.Append("<prefix/><suffix/><givenNameSound/><familyNameSound/>");
data.Append("</value></fields>");
data.Append("<fields><type>address</type>");
data.Append("<value><street>" + contact.Address + "</street>");
data.Append("<city>" + contact.City + "</city>");
data.Append("<stateOrProvince>" + contact.State + "</stateOrProvince>");
data.Append("<postalCode>" + contact.Zip + "</postalCode>");
data.Append("<country>United States</country>");
data.Append("<countryCode>US</countryCode>");
data.Append("</value></fields>");
data.Append("<fields><type>notes</type><value>" + contact.Note + "</value></fields>");
data.Append("<fields><type>link</type><value>" + contact.Website + "</value></fields>");
data.Append("<fields><type>email</type><value>" + contact.Email + "</value></fields>");
data.Append("<fields><type>phone</type><value>" + contact.BusinessPhone + "</value><flags>WORK</flags></fields>");
data.Append("<fields><type>phone</type><value>" + contact.BestPhone + "</value><flags>MOBILE</flags></fields>");
data.Append("<fields><type>phone</type><value>" + contact.SecondPhone + "</value><flags>PERSONAL</flags></fields>");
data.Append("<categories><category><name>GoGoContract</name></category></categories>");
data.Append("</contact>");
return data.ToString();
}
I need to update the Expiry Date and update the Cardholder Name on an existing card in Realex payments.
The hash value syntax should be in the following format:
Timestamp.merchantID.payerref.ref.expirydate.cardnumber
And here is an example of how it should look
20030516175919.yourmerchantid.mypayer.card01.1015.
When I run the following method I get the error:
"sha1hash incorrect - check your code and the Developers Documentation"
private string ReturnHash(string timeStamp, string merchantId, string payerRef, string reference, string expDate, string cardNum )
{
SHA1 hash = new SHA1Managed();
StringBuilder builder = new StringBuilder();
builder.Append(timeStamp).Append(".");
builder.Append(merchantId).Append(".");
builder.Append(payerRef).Append(".");
builder.Append(reference).Append(".");
builder.Append(expDate).Append(".");
builder.Append(cardNum );
string resultingHash = BitConverter.ToString(hash.ComputeHash(Encoding.UTF8.GetBytes(builder.ToString())));
resultingHash = BitConverter.ToString(hash.ComputeHash(Encoding.UTF8.GetBytes(resultingHash)));
return resultingHash;
}
What am I doing wrong?
Thank you for your message.
Could you try before running this line of code:
string resultingHash = BitConverter.ToString(hash.ComputeHash(Encoding.UTF8.GetBytes(builder.ToString())));
To make "resultingHash" all lowercase?
Also before running:
resultingHash = BitConverter.ToString(hash.ComputeHash(Encoding.UTF8.GetBytes(resultingHash)));
make "resultingHash" to lowercase as well.
Thanks,
Borja
var timeStamp = RealexDateFormatter.DateFormatForRealex();
var orderid = model.ORDER_ID;
var secret = ConfigurationManager.AppSettings["Appsecretkey"];
var merchantId = ConfigurationManager.AppSettings["AppMerchantId"];
var temp1 = FormsAuthentication.HashPasswordForStoringInConfigFile(
timeStamp + "." +
merchantId + "." +
orderid + "." +
model.AMOUNT + "." + "EUR", "sha1");
temp1 = temp1.ToLower();
var temp2 = temp1 + "." + secret;
var sha1hash = FormsAuthentication.HashPasswordForStoringInConfigFile(temp2, "sha1");
sha1hash = sha1hash.ToLower();`enter code here`
var url = "https://hpp.sandbox.realexpayments.com/pay?MERCHANT_ID="
+ ConfigurationManager.AppSettings["AppMerchantId"] +
"&ORDER_ID=" + orderid + "&CURRENCY=EUR" + "&AMOUNT=" + model.AMOUNT + "&TIMESTAMP=" + timeStamp + "&SHA1HASH=" + sha1hash + "&MERCHANT_RESPONSE_URL=http://deposit.projectstatus.in/Payment/Response";
I am trying the following code inside an ASP MVC Razor file:
var topic = ViewData["TopicID"];
var mustBeReplaced = string.Empty;
var topicValue = Model.Topic;
var replaceResult = string.Empty;
if (topic.Contains(topicValue)) {
mustBeReplaced = "value=\"" + topicValue + "\"";
replaceResult = mustBeReplaced + " selected=\"selected\"";
topic = topic.Replace(mustBeReplaced, replaceResult);
}
But I get an error message:
object' does not contain a definition for 'Contains' and the best extension method overload
var topic = ViewData["TopicID"];
Returns object. You need to cast to string.
Try this
var topic = (string)ViewData["TopicID"];
var mustBeReplaced = string.Empty;
var topicValue = "11111";
var replaceResult = string.Empty;
if (topic.Contains(topicValue))
{
mustBeReplaced = "value=\"" + topicValue + "\"";
replaceResult = mustBeReplaced + " selected=\"selected\"";
topic = topic.Replace(mustBeReplaced, replaceResult);
}