Reputation: 490
I am trying to make a call to 2checkout API. According to their documentation first I need to authenticate. All example code on their website is written in PHP. When I try the same using C# I am getting "Hash signature could not be authenticated" message from the server. Here is code-snipped from my code:
Encoding encoding = Encoding.UTF8;
string vendorCode = //My vendor code
string secretKey = //My secret key
byte[] secretBytes = encoding.GetBytes(secretKey);
date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
string input = vendorCode.Length.ToString() + vendorCode + date.Length.ToString() + date;
using (HMACMD5 keyedHash = new HMACMD5(secretBytes))
{
byte[] hashedBytes = keyedHash.ComputeHash(encoding.GetBytes(input));
string hash = Convert.ToBase64String(hashedBytes);
using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, apiUrl +
requestString))
{
request.Headers.Add("accept", "application/json");
string headerValue = "code=\"" + vendorCode + "\" date=\"" + date + "\" hash=\"" + hash + "\"";
request.Headers.Add("X-Avangate-Authentication", headerValue);
HttpResponseMessage httpResponse = await httpClient.SendAsync(request);
}
}
I am not sure what I am doing wrong. Is it the hash algorithm that I use or it is the text encoding? I tried several variants but without any success. I will be very grateful if someone helps me with this.
Upvotes: 0
Views: 351
Reputation: 31
The below code block works for me. Code slightly modified as per needs on basis of the documentation https://verifone.cloud/docs/2checkout/API-Integration/Webhooks/06Instant_Payment_Notification_%2528IPN%2529/IPN-code-samples#c__0023__00a0
string secretKey = "MYSECRETKEY";
string VendorCode = "MYVENDORCODE";
string requestDateTime = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss");
string plaintext = VendorCode.Length + VendorCode + requestDateTime.Length + requestDateTime;
using(HMACMD5 hmac = new HMACMD5(Encoding.ASCII.GetBytes(secretKey)))
{
byte[] hashBytes = hmac.ComputeHash(Encoding.ASCII.GetBytes(plaintext));
string signatureHash = BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
using (var httpClient = new HttpClient { BaseAddress = new Uri("https://api.avangate.com/rest/6.0/") })
{
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("X-Avangate-Authentication", $"code='{VendorCode}' date='{requestDateTime}' hash='{signatureHash}'");
// Make your requests to desired Api
}
}
Upvotes: 0