World Pay Payment gateway Integration In ASP.Net MVC using C# - worldpay

string xml = "<?xml version='1.0'? encoding='UTF-8'?><!DOCTYPE paymentService PUBLIC '-//WorldPay//DTD WorldPay PaymentService v1//EN''http://dtd.worldpay.com/paymentService_v1.dtd'><paymentService version='1.4' merchantCode='MYMERCHANTCODE'><submit><order orderCode='RecurringOrderCode'><description>Monthly subscription.</description><amount value='1399' currencyCode='EUR' exponent='2' /><orderContent>Your Original Order Content</orderContent> <paymentDetails><VISA-SSL> <cardNumber>4444333322221111</cardNumber><expiryDate> <date month='09' year='2019'/> </expiryDate> <cardHolderName>J. Shopper</cardHolderName><cvc>123</cvc> <cardAddress> <address> <street>47A Queensbridge Rd</street><postalCode>CB94BQ</postalCode><city>GB</city><countryCode>GB</countryCode><telephoneNumber>+44</telephoneNumber> </address> </cardAddress> </VISA-SSL> <session shopperIPAddress='100.100.100.100' id='0215ui8ib1' /> </paymentDetails></order></submit></paymentService>";
string url = "https://secure-test.worldpay.com/jsp/merchant/xml/paymentService.jsp";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
//string s = "id="+Server.UrlEncode(xml);
byte[] requestBytes = System.Text.Encoding.ASCII.GetBytes(xml);
req.Method = "POST";
req.ContentType = "text/xml;charset=utf-8";
req.ContentLength = requestBytes.Length;
Stream requestStream = req.GetRequestStream();
requestStream.Write(requestBytes, 0, requestBytes.Length);
requestStream.Close();
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream(), System.Text.Encoding.Default);
string backstr = sr.ReadToEnd();
sr.Close();
res.Close();
return View();
I am using this code to integrate the Worldpay payment gateway API i am getting this error on getting response from line HttpWebResponse res = (HttpWebResponse)req.GetResponse();
the error is -401 Authorization Required

You need to add your credentials to the request, probably HTTP basic auth. Can do it like this:
req.Headers[HttpRequestHeader.Authorization] = "Basic " +
Convert.ToBase64String(Encoding.ASCII.GetBytes(<username> + ":" + <password>));

Related

Docusign: Obtain the access token

Ref: https://developers.docusign.com/platform/auth/authcode/authcode-get-token/
I am having an issue on Step 2: Obtain Access Token
I am trying to get an access token. However I am getting the following error:
{
"error": "invalid_grant",
"error_description": "unsupported_grant_type"
}
whether its using c# code or using PostMan I am getting the error above.
In PostMan
URL: https://account-d.docusign.com/oauth/token
Method: Post
Headers
Authorization: BASIC BASE64_COMBINATION_OF_INTEGRATION_AND_SECRET_KEYS
Content_Type: application/json;charset=utf-8
Body: I tried form-data, x.www.form-urlencoded, raw... all are the same
grant_type: authorization_code
code: My_AUTHORIZATION_CODE
I also tried getting the access token in the call back page when I get the Authorization Code.
protected void Page_Load(object sender, EventArgs e)
{
var url = ConfigurationManager.AppSettings["DocuSign.TokenEndPoint"];
var data = $"grant_type=authorization_code=&{Request.QueryString["Code"]}";
WebRequest req = WebRequest.Create(url);
req.Method = "POST";
req.ContentLength = data.Length;
req.ContentType = "application/json; charset=UTF-8";
UTF8Encoding enc = new UTF8Encoding();
var code64 = Convert.ToBase64String(enc.GetBytes($"{ConfigurationManager.AppSettings["DocuSign.ClientId"]}:{ConfigurationManager.AppSettings["DocuSign.ClientSecret"]}"));
req.Headers.Add("Authorization", "Basic " + code64);
using (Stream ds = req.GetRequestStream())
{
ds.Write(enc.GetBytes(data), 0, data.Length);
}
WebResponse wr = req.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();
Response.Write(content);
}
Your content_type should be application/x-www-form-urlencoded
the following line was wrong:
var data = $"grant_type=authorization_code=&{Request.QueryString["Code"]}";
Changed to
var data = $"grant_type=authorization_code&code={Request.QueryString["Code"]}";
I was missing code=

Microsoft Face Detect API code example Bad Request

I have been trying to solve this bad request error. I am able to make the request call and Azure reports total calls correctly and also reports total errors.
I can not get this code example to work; however if I send this via their online console all is fine:
static async void MakeRequest()
{
string key1 = "YourKey"; // azure the one should work
string data = "https://pbs.twimg.com/profile_images/476054279438868480/vvv5YG0Q.jpeg";
var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
// Request parameters
queryString["returnFaceId"] = "true";
// Request headers
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", key1);
Console.Beep();
var uri = "https://westus.api.cognitive.microsoft.com/face/v1.0/detect?" + queryString;
//string statusURL = HttpContext.Current.Request.Url.Host;
//console.WriteLine("Your Status URL address is :" + statusURL);
HttpResponseMessage response;
// Request body
// byte[] byteData = Encoding.UTF8.GetBytes("{url: https://pbs.twimg.com/profile_images/476054279438868480/vvv5YG0Q.jpeg}");
byte[] byteData = Encoding.UTF8.
GetBytes("{"+ "url"+":"+"https://pbs.twimg.com/profile_images/476054279438868480/vvv5YG0Q.jpeg" + "}");
using (var content = new ByteArrayContent(byteData))
{
content.Headers.ContentType =
new MediaTypeHeaderValue("application/json");
response = await client.PostAsync(uri, content);
}
HttpRequestMessage request =
new HttpRequestMessage(HttpMethod.Post, uri);
request.Content = new StringContent("{body}",
Encoding.UTF8,
"application/json");
//CONTENT-TYPE header
await client.SendAsync(request)
.ContinueWith(responseTask =>
{
Console.WriteLine("Response: {0}", responseTask.Result);
Console.WriteLine("-----------------------------------");
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("End of Post return from MS");
Console.WriteLine("Hit ENTER to exit...");
Console.ReadKey();
});
}// end of Make request
Your JSON is malformed. Your fields and non-scalar fields must be quoted. You also have some unnecessary code. Here's code that works:
static async void MakeRequest()
{
string key1 = "YourKey"; // azure the one should work
string imageUri = "https://pbs.twimg.com/profile_images/476054279438868480/vvv5YG0Q.jpeg";
var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
// Request parameters
queryString["returnFaceId"] = "true";
// Request headers
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", key1);
var uri = "https://westus.api.cognitive.microsoft.com/face/v1.0/detect?" + queryString;
string body = "{\"url\":\"" + imageUri + "\"}";
using (var content = new StringContent(body, Encoding.UTF8, "application/json"))
{
await client.PostAsync(uri, content)
.ContinueWith(async responseTask =>
{
var responseBody = await responseTask.Result.Content.ReadAsStringAsync();
Console.WriteLine("Response: {0}", responseBody);
Console.WriteLine("-----------------------------------");
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("End of Post return from MS");
Console.WriteLine("Hit ENTER to exit...");
Console.ReadKey();
});
}
}// end of Make request
If you're using Visual Studio, I would recommend the NuGet package as this will handle much of the mundane details for you, including C# types for responses.

Can't delete Azure Storage Table using Azure REST API

I am getting an error "Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature."
I followed the authorization tutorial provided by Microsoft, Delete Table, Authentication for the Azure Storage Services.
Am I missing anything?
It seems that you’d like to delete table via rest api.
DELETE https://myaccount.table.core.windows.net/Tables('mytable')
the following sample works fine on my side, please refer to the code to generate the signature.
string StorageAccount = "account name here";
string StorageKey = "account key here";
string tablename = "table name";
string requestMethod = "DELETE";
string mxdate = "";
string storageServiceVersion = "2015-12-11";
protected void Button1_Click(object sender, EventArgs e)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(string.Format(CultureInfo.InvariantCulture,
"https://{0}.table.core.windows.net/Tables('{1}')",
StorageAccount, tablename));
req.Method = requestMethod;
//specify request header
string AuthorizationHeader = generateAuthorizationHeader();
req.Headers.Add("Authorization", AuthorizationHeader);
req.Headers.Add("x-ms-date", mxdate);
req.Headers.Add("x-ms-version", storageServiceVersion);
req.ContentType = "application/json";
req.Accept = "application/json;odata=minimalmetadata";
using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
{
}
}
public string generateAuthorizationHeader()
{
mxdate = DateTime.UtcNow.ToString("R");
string canonicalizedResource = $"/{StorageAccount}/Tables('{tablename}')";
string contentType = "application/json";
string stringToSign = $"{requestMethod}\n\n{contentType}\n{mxdate}\n{canonicalizedResource}";
HMACSHA256 hmac = new HMACSHA256(Convert.FromBase64String(StorageKey));
string signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
String authorization = String.Format("{0} {1}:{2}",
"SharedKey",
StorageAccount,
signature
);
return authorization;
}

Get Access token from Spotify api

I'm trying to get a access token from this endpoint using asp.net: https://accounts.spotify.com/api/token
The token i get back has Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}".
When creating my app over att Spotify Developer i stated my Redirect Uri as http://localhost:59486/ which is my Project Url.
What am i doing wrong?
I have borrowed this method from https://hendrikbulens.wordpress.com/2015/01/07/c-and-the-spotify-web-api-part-i/
private async Task<string> GetAccessToken()
{
SpotifyToken token = new SpotifyToken();
string postString = string.Format("grant_type=client_credentials");
byte[] byteArray = Encoding.UTF8.GetBytes(postString);
string url = "https://accounts.spotify.com/api/token";
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
request.Headers.Add("Authorization", "Basic YjlkZj****************************************jQ2YjM3MjE5MDE=");
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
using (WebResponse response = await request.GetResponseAsync())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
string responseFromServer = reader.ReadToEnd();
token = JsonConvert.DeserializeObject<SpotifyToken>(responseFromServer);
}
}
}
}
return token.access_token;
}
EDIT:
This is my Http request:
spotify.com/api/token HTTP/1.1
Authorization: Basic Yjlk....................5MDE=
Content-Type: application/x-www-form-urlencoded
Host: accounts.spotify.com
Content-Length: 29
Expect: 100-continue
Connection: Keep-Alive
grant_type=client_credentials

getting 403 forbidden webexception for azure blob put request

I am using this code to upload some text directly to azure blob using rest api. I am getting an webexception 403 forbidden. Can someone plaese tell me where am i going wrong in my code
private String CreateAuthorizationHeader(String canonicalizedString, CloudBlob blob)
{
String signature = string.Empty;
using (HMACSHA256 hmacSha256 = new HMACSHA256())
{
Byte[] dataToHmac = System.Text.Encoding.UTF8.GetBytes(canonicalizedString);
signature = Convert.ToBase64String(hmacSha256.ComputeHash(dataToHmac));
}
String authorizationHeader = String.Format(CultureInfo.InvariantCulture, "{0} {1}:{2}", "SharedKeyLite", myaccount, signature);
return authorizationHeader;
}
private void PutBlob(String containerName, String blobName , CloudBlob blob)
{
String requestMethod = "PUT";
String urlPath = String.Format("{0}", blobName);
String storageServiceVersion = "2009-10-01";
String dateInRfc1123Format = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture);
// if (uploadPST.HasFile)
// {
string content = "Sample file";
// Stream content = uploadPST.FileBytes;
UTF8Encoding utf8Encoding = new UTF8Encoding();
Byte[] blobContent = utf8Encoding.GetBytes(content);
Int32 blobLength = blobContent.Length;
const String blobType = "BlockBlob";
/* String canonicalizedHeaders = String.Format(
"x-ms-blob-type:{0}\nx-ms-date:{1}\nx-ms-version:{2}",
blobType,
dateInRfc1123Format,
storageServiceVersion);*/
String canonicalizedHeaders = String.Format(
"x-ms-date:{0}\nx-ms-meta-m1:{1}\nx-ms-meta-m1:{2}",
dateInRfc1123Format,
"v1",
"v2");
String canonicalizedResource = String.Format("/{0}/{1}", myaccount, urlPath);
String stringToSign = String.Format(
"{0}\n\n{1}\n\n{2}\n{3}",
requestMethod,
"text/plain; charset=UTF-8",
canonicalizedHeaders,
canonicalizedResource);
String authorizationHeader = CreateAuthorizationHeader(stringToSign, blob);
Uri uri = new Uri(CloudStorageAccount.FromConfigurationSetting("DataConnectionString").BlobEndpoint + "/" + urlPath);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = requestMethod;
// request.Headers.Add("x-ms-blob-type", blobType);
request.Headers.Add("x-ms-date", dateInRfc1123Format);
// request.Headers.Add("x-ms-version", storageServiceVersion);
request.Headers.Add("Authorization", authorizationHeader);
request.ContentLength = blobLength;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(blobContent ,0 ,blobLength);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
String ETag = response.Headers["ETag"];
}
// }
}
First, you construct an HMACSHA256 object using the default constructor -- this causes a random key to be generated and used for signing. What you want is the overload which accepts a string - and pass the azure account key.
Still, signing the request 'manually' can be tricky, as there are a lot of things to do and it's easy to mess up or forget something. Instead, I recommend you use the SignRequest method of StorageCredentialsAccountAndKey class (msdn doc) For instance;
// ...there exists a request object, and strings for the account name and key
var creds = new StorageCredentialsAccountAndKey(accountName, accountKey);
creds.SignRequest(request);
This will do everything needed to sign the request properly, including creating a canonicalized headers string, creating a date with the correct format, etc.

Resources