asp.net amazon itemsearch - asp.net

I'm using visual studio 2008 and trying to do API itemsearch like books or something.
I am using just accessKeyId, but when I click my "search" button to search books, then comes signature error.
Do I need to use secretKeyID also?
I just created new ASP.Net web site in visual studio Or I have to use AWS SDK for.Net package?
Can somebody please give a good advice.
Thanks!

Signature error means you did not create a request signature properly. You should use the SprightlySoft AWS Component for .NET. It's free and it supports the Product Advertising API. Get it at http://sprightlysoft.com/. The AWS SDK for.NET does not work with the Product Advertising API.
Here is an example of calling ItemSearch with the SprightlySoft component.
//Product Advertising API, ItemSearch: http://docs.amazonwebservices.com/AWSECommerceService/2010-10-01/DG/ItemSearch.html
SprightlySoftAWS.REST MyREST = new SprightlySoftAWS.REST();
String RequestURL;
RequestURL = "https://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&Operation=ItemSearch&Version=2010-10-01";
RequestURL += "&AWSAccessKeyId=" + System.Uri.EscapeDataString(TextBoxAWSAccessKeyId.Text) + "&SignatureVersion=2&SignatureMethod=HmacSHA256&Timestamp=" + Uri.EscapeDataString(DateTime.UtcNow.ToString("yyyy-MM-dd\\THH:mm:ss.fff\\Z"));
RequestURL += "&Actor=" + System.Uri.EscapeDataString("Tom Cruise");
RequestURL += "&SearchIndex=DVD";
RequestURL += "&ResponseGroup=" + System.Uri.EscapeDataString("ItemAttributes,Reviews");
RequestURL += "&Sort=salesrank";
RequestURL += "&ItemPage=1";
String RequestMethod;
RequestMethod = "GET";
String SignatureValue;
SignatureValue = MyREST.GetSignatureVersion2Value(RequestURL, RequestMethod, "", TextBoxAWSSecretAccessKey.Text);
RequestURL += "&Signature=" + System.Uri.EscapeDataString(SignatureValue);
Boolean RetBool;
RetBool = MyREST.MakeRequest(RequestURL, RequestMethod, null);
System.Diagnostics.Debug.Print(MyREST.LogData);
String ResponseMessage = "";
if (RetBool == true)
{
System.Xml.XmlDocument MyXmlDocument;
System.Xml.XmlNamespaceManager MyXmlNamespaceManager;
System.Xml.XmlNode MyXmlNode;
System.Xml.XmlNodeList MyXmlNodeList;
MyXmlDocument = new System.Xml.XmlDocument();
MyXmlDocument.LoadXml(MyREST.ResponseString);
MyXmlNamespaceManager = new System.Xml.XmlNamespaceManager(MyXmlDocument.NameTable);
MyXmlNamespaceManager.AddNamespace("amz", "http://webservices.amazon.com/AWSECommerceService/2010-10-01");
MyXmlNodeList = MyXmlDocument.SelectNodes("amz:ItemSearchResponse/amz:Items/amz:Item", MyXmlNamespaceManager);
if (MyXmlNodeList.Count == 0)
{
ResponseMessage = "No items exist.";
}
else
{
foreach (System.Xml.XmlNode ItemXmlNode in MyXmlNodeList)
{
MyXmlNode = ItemXmlNode.SelectSingleNode("amz:ItemAttributes/amz:Title", MyXmlNamespaceManager);
ResponseMessage += "Title = " + MyXmlNode.InnerText;
MyXmlNode = ItemXmlNode.SelectSingleNode("amz:ItemAttributes/amz:ListPrice/amz:FormattedPrice", MyXmlNamespaceManager);
ResponseMessage += " ListPrice = " + MyXmlNode.InnerText;
ResponseMessage += Environment.NewLine;
}
}
MessageBox.Show(ResponseMessage);
}
else
{
MessageBox.Show(MyREST.ResponseStringFormatted);
}

Related

Oauth 401 Error invalid signature when requesting to woocommerce rest api with httpclient .net core

First of all I know I can use trusted libraries to generate oAuth header signature but I spent a lot of time to generate this signature and I want to know why it's not working.
I have ConsumerKey and ConsumerSecret to access woocommerce rest api.
I write a method to generate BaseSignatureString and another method to get HMAC-SHA1 :
public static string GetoAuthToken(string conKey, string conSecret)
{
string timestamp = ((int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString();
string nonce = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(timestamp
+ timestamp + timestamp));
var signatureBaseString = "GET&" + Uri.EscapeDataString("https://loomina.ir/wp-json/wc/v3/products") + "&";
signatureBaseString += Uri.EscapeDataString($"oauth_consumer_key={conKey}&");
signatureBaseString += Uri.EscapeDataString($"oauth_nonce={nonce}&");
signatureBaseString += Uri.EscapeDataString($"oauth_signature_method=HMAC-SHA1&");
signatureBaseString += Uri.EscapeDataString($"oauth_timestamp={timestamp}&");
signatureBaseString += Uri.EscapeDataString($"oauth_version=1.0");
string SHA1HASH = GetSha1Hash(conSecret + "&" , signatureBaseString);
string Header = $"oauth_consumer_key=\"{conKey}\",oauth_timestamp=\"{timestamp}\",oauth_signature_method=\"HMAC-SHA1',oauth_nonce=\"{nonce}\",oauth_version=\"1.0\",oauth_signature=\"{SHA1HASH}\"";
return Header;
}
Get SHA1 Hash :
public static string GetSha1Hash(string key, string baseSignatureString)
{
var encoding = new ASCIIEncoding();
byte[] keyBytes = encoding.GetBytes(key);
byte[] messageBytes = encoding.GetBytes(baseSignatureString);
string Sha1Result = string.Empty;
using (HMACSHA1 SHA1 = new HMACSHA1(keyBytes))
{
var Hashed = SHA1.ComputeHash(messageBytes);
Sha1Result = Convert.ToBase64String(Hashed);
}
return Sha1Result;
}
Request part :
var oAuthSignature = Utility.GetoAuthToken(websites.CustomerKey, websites.CustomerSecret);
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("OAuth", oAuthSignature);
var response = await _client.GetAsync($"{websites.Url}/wp-json/wc/v3/products/");
var result = await response.Content.ReadAsStringAsync();
The status of request is 401 Not Authorized (Invalid signature)

How to add file attachment to Email message sent from Razor page (with ASP.NET Core and MailKit)

The following is a method for sending an Email from a Razor page in ASP.NET Core. I need to use MailKit since System.Net.Mail is not available in ASP.NET Core.
Despite much research, I haven't been able to figure out a way to include the image to the Email. Note that it doesn't have to be an attachment - embedding the image will work.
public ActionResult Contribute([Bind("SubmitterScope, SubmitterLocation, SubmitterItem, SubmitterCategory, SubmitterEmail, SubmitterAcceptsTerms, SubmitterPicture")]
EmailFormModel model)
{
if (ModelState.IsValid)
{
try
{
var emailName= _appSettings.EmailName;
var emailAddress = _appSettings.EmailAddress;
var emailPassword = _appSettings.EmailPassword;
var message = new MimeMessage();
message.From.Add(new MailboxAddress(emailName, emailAddress));
message.To.Add(new MailboxAddress(emailName, emailAddress));
message.Subject = "Record Submission From: " + model.SubmitterEmail.ToString();
message.Body = new TextPart("plain")
{
Text = "Scope: " + model.SubmitterScope.ToString() + "\n" +
"Zip Code: " + model.SubmitterLocation.ToString() + "\n" +
"Item Description: " + model.SubmitterItem.ToString() + "\n" +
"Category: " + model.SubmitterCategory + "\n" +
"Submitted By: " + model.SubmitterEmail + "\n" +
// This is the file that should be attached.
//"Picture: " + model.SubmitterPicture + "\n" +
"Terms Accepted: " + model.SubmitterAcceptsTerms + "\n"
};
using (var client = new SmtpClient())
{
client.Connect("smtp.gmail.com", 587);
// Note: since we don't have an OAuth2 token, disable
// the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove("XOAUTH2");
// Note: only needed if the SMTP server requires authentication
client.Authenticate(emailAddress, emailPassword);
client.Send(message);
client.Disconnect(true);
return RedirectToAction("Success");
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message + ": " + ex.StackTrace);
return RedirectToAction("Failure");
}
}
else
{
return View();
}
}
This is from the FAQ on Mailkit github repo, and seems to cover the full process.
https://github.com/jstedfast/MailKit/blob/master/FAQ.md#CreateAttachments
var message = new MimeMessage ();
message.From.Add (new MailboxAddress ("Joey", "joey#friends.com"));
message.To.Add (new MailboxAddress ("Alice", "alice#wonderland.com"));
message.Subject = "How you doin?";
// create our message text, just like before (except don't set it as the message.Body)
var body = new TextPart ("plain") {
Text = #"Hey Alice,
What are you up to this weekend? Monica is throwing one of her parties on
Saturday and I was hoping you could make it.
Will you be my +1?
-- Joey
"
};
// create an image attachment for the file located at path
var attachment = new MimePart ("image", "gif") {
ContentObject = new ContentObject (File.OpenRead (path), ContentEncoding.Default),
ContentDisposition = new ContentDisposition (ContentDisposition.Attachment),
ContentTransferEncoding = ContentEncoding.Base64,
FileName = Path.GetFileName (path)
};
// now create the multipart/mixed container to hold the message text and the
// image attachment
var multipart = new Multipart ("mixed");
multipart.Add (body);
multipart.Add (attachment);
// now set the multipart/mixed as the message body
message.Body = multipart;

401 System.UnauthorizedAccessException when access Dropbox With SharpBox API

The code
config = CloudStorage.GetCloudConfigurationEasy(nSupportedCloudConfigurations.DropBox)
as DropBoxConfiguration;
//config.AuthorizationCallBack = new Uri("http://localhost:61926/DBoxDemo.aspx");
requestToken = DropBoxStorageProviderTools.GetDropBoxRequestToken(config, "KEY", "SECRET");
//Session["requestToken"] = requestToken;
string AuthoriationUrl = DropBoxStorageProviderTools.GetDropBoxAuthorizationUrl(
config, requestToken);
Process.Start(AuthoriationUrl);
accessToken = DropBoxStorageProviderTools.ExchangeDropBoxRequestTokenIntoAccessToken(
config, "xxxxxxxxxxxxx", "xxxxxxxxxxxxx", requestToken);
CloudStorage dropBoxStorage = new CloudStorage();
var storageToken = dropBoxStorage.Open(config, accessToken);
var publicFolder = dropBoxStorage.GetFolder("/");
// upload a testfile from temp directory into public folder of DropBox
String srcFile = Environment.ExpandEnvironmentVariables(#"C:\Test\MyTestFile.txt");
var rep = dropBoxStorage.UploadFile(srcFile, publicFolder);
MessageBox.Show("Uploaded Successfully..");
**dropBoxStorage.DownloadFile("/MyTestFile.txt",
Environment.ExpandEnvironmentVariables("D:\\test"));**
MessageBox.Show("Downloaded Successfully..");
dropBoxStorage.Close();
This is the Error shown in Visual Studio.
SharpBox has a bug that only occurs in .NET 4.5, because the behavior of the class System.Uri has changed from 4.0 to 4.5.
The method GetDownloadFileUrlInternal() in DropBoxStorageProviderService.cs generates an incorrect URL, because it changes a slash in %2f. In .NET 4.0, this URL will be converted correctly back through the System.Uri object in the method GenerateSignedUrl() in OAuthUrlGenerator.cs.
I have changed the method GetDownloadFileUrlInternal() from this...
public static String GetDownloadFileUrlInternal(IStorageProviderSession session, ICloudFileSystemEntry entry)
{
// cast varibales
DropBoxStorageProviderSession dropBoxSession = session as DropBoxStorageProviderSession;
// gather information
String rootToken = GetRootToken(dropBoxSession);
String dropboxPath = GenericHelper.GetResourcePath(entry);
// add all information to url;
String url = GetUrlString(DropBoxUploadDownloadFile, session.ServiceConfiguration) + "/" + rootToken;
if (dropboxPath.Length > 0 && dropboxPath[0] != '/')
url += "/";
url += HttpUtilityEx.UrlEncodeUTF8(dropboxPath);
return url;
}
...to this...
public static String GetDownloadFileUrlInternal(IStorageProviderSession session, ICloudFileSystemEntry entry)
{
// cast varibales
DropBoxStorageProviderSession dropBoxSession = session as DropBoxStorageProviderSession;
// gather information
String rootToken = GetRootToken(dropBoxSession);
// add all information to url;
String url = GetUrlString(DropBoxUploadDownloadFile, session.ServiceConfiguration) + "/" + rootToken;
ICloudFileSystemEntry parent = entry.Parent;
String dropboxPath = HttpUtilityEx.UrlEncodeUTF8(entry.Name);
while(parent != null)
{
dropboxPath = HttpUtilityEx.UrlEncodeUTF8(parent.Name) + "/" + dropboxPath;
parent = parent.Parent;
}
if (dropboxPath.Length > 0 && dropboxPath[0] != '/')
url += "/";
url += dropboxPath;
return url;
}
and currently it works with .NET 4.5. It may exist a better way to fix the problem, but currently no misconduct noticed.

Amazon CloudFront invalidation in ASP.Net

I am not sure how to send a request using ASP.Net to Amazon CloudFront to invalidate an object.
The details are here http://docs.amazonwebservices.com/AmazonCloudFront/latest/DeveloperGuide/index.html?Invalidation.html
but I am not sure how to implement this in ASP.Net.
The accepted answer no longer works as of the latest version of the AWS SDK for .NET (1.5.8.0). This should do the trick:
using Amazon;
using Amazon.CloudFront.Model;
...
var client = AWSClientFactory.CreateAmazonCloudFrontClient(accessKey, secretKey);
client.CreateInvalidation(new CreateInvalidationRequest {
DistributionId = distributionID,
InvalidationBatch = new InvalidationBatch {
Paths = new Paths {
Quantity = arrayofpaths.Length,
Items = arrayofpaths.ToList()
},
CallerReference = DateTime.Now.Ticks.ToString()
}
});
Got it working, here it is if anyone else finds it useful.
public static void InvalidateContent(string distributionId, string fileName)
{
string httpDate = Helpers.GetHttpDate();
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = #"<InvalidationBatch>" +
" <Path>/" + fileName + "</Path>" +
" <CallerReference>" + httpDate + "</CallerReference>" +
"</InvalidationBatch>";
byte[] data = encoding.GetBytes(postData);
// Prepare web request...
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://cloudfront.amazonaws.com/2010-08-01/distribution/" + distributionId + "/invalidation");
webRequest.Method = "POST";
webRequest.ContentType = "text/xml";
webRequest.Headers.Add("x-amz-date", httpDate);
Encoding ae = new UTF8Encoding();
HMACSHA1 signature = new HMACSHA1(ae.GetBytes(GlobalSettings.AWSSecretAccessKey.ToCharArray()));
string b64 = Convert.ToBase64String(signature.ComputeHash(ae.GetBytes(webRequest.Headers["x-amz-date"].ToCharArray())));
webRequest.Headers.Add(HttpRequestHeader.Authorization, "AWS" + " " + GlobalSettings.AWSAccessKeyId + ":" + b64);
webRequest.ContentLength = data.Length;
Stream newStream = webRequest.GetRequestStream();
// Send the data.
newStream.Write(data, 0, data.Length);
newStream.Close();
}
/// <summary>
/// Gets a proper HTTP date
/// </summary>
public static string GetHttpDate()
{
// Setting the Culture will ensure we get a proper HTTP Date.
string date = System.DateTime.UtcNow.ToString("ddd, dd MMM yyyy HH:mm:ss ", System.Globalization.CultureInfo.InvariantCulture) + "GMT";
return date;
}
Here's a python version of the above, if anyone finds it useful
from datetime import datetime
import urllib2, base64, hmac, hashlib
def getHTTPDate():
return datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S UTC")
def submitInvalidationRequest(fileName,distributionId):
url = "https://cloudfront.amazonaws.com/2010-08-01/distribution/" + distributionId + "/invalidation"
httpDate = getHTTPDate();
postData = "<InvalidationBatch>" +"<Path>/" + fileName + "</Path>" +"<CallerReference>" + httpDate + "</CallerReference>" +"</InvalidationBatch>";
sig = hmac.new(AWSSecretAccessKey, unicode(httpDate), hashlib.sha1)
headers = {"ContentType": "text/xml",
"x-amz-date": httpDate,
"Authorization":"AWS " + AWSAccessKeyId + ":" + base64.b64encode( sig.digest() )}
req = urllib2.Request(url,postData,headers)
return urllib2.urlopen(req).read()
using the AWSSDK .net api wrapper from amazon makes this task even easier.
using Amazon.CloudFront.Model;
...
var client = Amazon.AWSClientFactory.CreateAmazonCloudFrontClient(ConfigurationManager.AppSettings["Aws.AccessKey"],
ConfigurationManager.AppSettings["Aws.SecretKey"]);
var request = new PostInvalidationRequest();
request.DistributionId = ConfigurationManager.AppSettings["Cdn.DistributionId"];
request.InvalidationBatch = new InvalidationBatch();
request.InvalidationBatch.CallerReference = new Guid().ToString();
request.InvalidationBatch.Paths = PathsInput.Text.Split(new[]{'\n','\r'},StringSplitOptions.RemoveEmptyEntries).ToList();
var response = client.PostInvalidation(request);
Here's perl:
use warnings;
use strict;
use HTTP::Date;
use Digest::SHA qw(hmac_sha1);
use LWP::UserAgent;
use MIME::Base64;
use Encode qw(encode_utf8);
#ARGV == 4 || die "usage: $0 url distribution_id accesskey secretkey\n";
my $invalid_url = $ARGV[0];
my $distribution_id = $ARGV[1];
my $accesskey = $ARGV[2];
my $secretkey = $ARGV[3];
my $url = "https://cloudfront.amazonaws.com/2010-11-01/distribution/$distribution_id/invalidation";
my $date = time2str;
my $post_data = <<HERE;
<?xml version="1.0" encoding="UTF-8"?>
<InvalidationBatch>
<Path>$invalid_url</Path>
<CallerReference>$date</CallerReference>
</InvalidationBatch>
HERE
my $sig = encode_base64(hmac_sha1(encode_utf8($date),encode_utf8($secretkey)));
my $browser = LWP::UserAgent->new;
my $res = $browser->post($url,
"Content" => $post_data,
"ContentType" => "text/xml",
"x-amz-date" => $date,
"Authorization" => "AWS $accesskey:$sig");
print $res->status_line, "\n", $res->content;

What is the best way to accept a credit card in ASP.NET? (Between ASP.NET and Authorize.NET)

I'm new to creating commerce websites, and now that I need to sell software over the internet, I'm not sure where to start.
I'm using ASP.NET and am considering using Authorize.NET to validate and process the credit cards.
I'm looking for a stable, trusted solution that I can install on a single server. My secondary goal (besides selling products online) is to become familiar with shopping cart software that is popular, and in use by large businesses. Perhaps I should start with MS Commerce server?
There are a million options here, but if you are writing the code, the easiest way code-wise is to use http://sharpauthorize.com/
Authorize.Net is Very easy to implement with ASP.NET
Basically you can make transaction in 3-4 ways:
Simple Checkout Through Button like Paypal (http://developer.authorize.net/api/simplecheckout/)
Direct Post : Suppose you little bit more customization than Simple CheckOut. Create a checkout form that posts directly to Authorize.Net http://developer.authorize.net/api/simplecheckout/
Eg:
<h1><%=ViewData["message"] %></h1>
<%using (Html.BeginSIMForm("http://YOUR_SERVER.com/home/sim",
1.99M,"YOUR_API_LOGIN","YOUR_TRANSACTION_KEY",true)){%>
<%=Html.CheckoutFormInputs(true)%>
<%=Html.Hidden("order_id","1234") %>
<input type = "submit" value = "Pay" />
<%}%>
SIM (Server Integration)
AIM (Advance Integration Method): Give full control & customization.
CIM ( store Customer card no & info on Auth.NET server with tokanization)
*Below is a sample of CIM function to make a transaction, AIM is very much similar to CIM only difference is tokanization *
using ProjName.AuthApiSoap; // USE AUth Webserice Reference
public Tuple<string, string, string> CreateTransaction(long profile_id, long payment_profile_id, decimal amt, string DDD)
{
CustomerProfileWS.ProfileTransAuthCaptureType auth_capture = new CustomerProfileWS.ProfileTransAuthCaptureType();
auth_capture.customerProfileId = profile_id;
auth_capture.customerPaymentProfileId = payment_profile_id;
auth_capture.amount = amt;//1.00m;
auth_capture.order = new CustomerProfileWS.OrderExType();
POSLib.POSManager objManager = new POSLib.POSManager();
auth_capture.order.invoiceNumber = objManager.GetTimestamp(DateTime.Now);
DateTime now = DateTime.Now;
auth_capture.order.description = "Service " + DDD;
CustomerProfileWS.ProfileTransactionType trans = new CustomerProfileWS.ProfileTransactionType();
trans.Item = auth_capture;
CustomerProfileWS.CreateCustomerProfileTransactionResponseType response = SoapAPIUtilities.Service.CreateCustomerProfileTransaction(SoapAPIUtilities.MerchantAuthentication, trans, null);
string AuthTranMsg = "";
string AuthTranCode = "";
for (int i = 0; i < response.messages.Length; i++)
{
AuthTranMsg = response.messages[i].text; // To Get Message n for loop to check the [i] is not empty
}
for (int i = 0; i < response.messages.Length; i++)
{
AuthTranCode = response.messages[i].code; // To Get Code n for loop to check the [i] is not empty
}
var tCompResp = new Tuple<string, string, string>(AuthTranCode, AuthTranMsg, response.directResponse);
return tCompResp;
}
This is how to split the Reponse Msg (Format and Order will be FIXED for all transaction/ on web service responsed )
var tResp = objManager.CreateTransaction(profID, paymProfID, Convert.ToDecimal(PmtToday), DDD);
string respCCNo = "";
string RespCCType = "";
string InvoiceNo = "";
string transType = "";
string approvalCode = "";
string AmtRequested = "";
string respName = "";
string respReasonText = "";
string respMD5Hash = "";
string respEmailId = "";
string respReasonCode = "";
string respMethod = "";
string respAVSResultCode = "";
string responseCode = "";
string transactionId = "0";
if (!string.IsNullOrEmpty(tCompResp.Item3))
{
string[] arrRespParts = tCompResp.Item3.Replace("|", "").Split(',');
responseCode = arrRespParts[0];
respReasonCode = arrRespParts[2];
respReasonText = arrRespParts[3];
approvalCode = arrRespParts[4];
respAVSResultCode = arrRespParts[5];
transactionId = arrRespParts[6].Replace("|", "");
InvoiceNo = arrRespParts[7];
AmtRequested = arrRespParts[9];
transType = arrRespParts[10];
respMethod = arrRespParts[11];
respName = arrRespParts[13] + " " + arrRespParts[14];
respEmailId = arrRespParts[23];
respMD5Hash = arrRespParts[37];
respCCNo = arrRespParts[50];
RespCCType = arrRespParts[51];
}
==================================AIM Code
public Tuple<string, string, string> ECheckCreateTransAIM(string amount, string bankRoutingNo, string bankAccNo, string bankAccType, string bankName, string bankAccName, string echeckType, bool isCustomerEmail, string customerEmail, string mechantEMail)
{
//CustomValidator1.ErrorMessage = "";
string AuthNetVersion = "3.1"; // Contains CCV support
WebClient webClientRequest = new WebClient();
System.Collections.Specialized.NameValueCollection InputObject = new System.Collections.Specialized.NameValueCollection(30);
System.Collections.Specialized.NameValueCollection ReturnObject = new System.Collections.Specialized.NameValueCollection(30);
byte[] ReturnBytes;
string[] ReturnValues;
string ErrorString;
InputObject.Add("x_version", AuthNetVersion);
InputObject.Add("x_delim_data", "True");
InputObject.Add("x_login", MERCHANT_NAME);
InputObject.Add("x_tran_key", TRANSACTION_KEY);
InputObject.Add("x_relay_response", "False");
//----------------------Set to False to go Live--------------------
InputObject.Add("x_test_request", "False");
//---------------------------------------------------------------------
InputObject.Add("x_delim_char", ",");
InputObject.Add("x_encap_char", "|");
if (isCustomerEmail)
{
InputObject.Add("x_email", customerEmail);
InputObject.Add("x_email_customer", "TRUE"); //Emails Customer
}
InputObject.Add("x_merchant_email", mechantEMail);
// FOR echeck
InputObject.Add("x_bank_aba_code", bankRoutingNo);
InputObject.Add("x_bank_acct_num", bankAccNo);
InputObject.Add("x_bank_acct_type", bankAccType);
InputObject.Add("x_bank_name", bankName);
InputObject.Add("x_bank_acct_name", bankAccName);
InputObject.Add("x_method", "ECHECK");
InputObject.Add("x_type", "AUTH_CAPTURE");
InputObject.Add("x_amount", string.Format("{0:c2}", Convert.ToDouble(amount)));
// Currency setting. Check the guide for other supported currencies
//needto change it to Actual Server URL
//Set above Testmode=off to go live
webClientRequest.BaseAddress = eCheckBaseAddress; //"https://apitest.authorize.net/soap/v1/Service.asmx"; //"https://secure.authorize.net/gateway/transact.dll";
ReturnBytes = webClientRequest.UploadValues(webClientRequest.BaseAddress, "POST", InputObject);
ReturnValues = System.Text.Encoding.ASCII.GetString(ReturnBytes).Split(",".ToCharArray());
if (ReturnValues[0].Trim(char.Parse("|")) == "1") // Succesful Transaction
{
//AuthNetCodeLabel.Text = ReturnValues[4].Trim(char.Parse("|")); // Returned Authorisation Code
//AuthNetTransIDLabel.Text = ReturnValues[6].Trim(char.Parse("|")); // Returned Transaction ID
var tCompResp = new Tuple<string, string, string>("I00001", ReturnValues[3].Trim(char.Parse("|")), string.Join(",", ReturnValues));
return tCompResp;
}
else
{
// Error!
ErrorString = ReturnValues[3].Trim(char.Parse("|")) + " (" + ReturnValues[2].Trim(char.Parse("|")) + ")";
if (ReturnValues[2].Trim(char.Parse("|")) == "45")
{
if (ErrorString.Length > 1)
ErrorString += "<br />n";
// AVS transaction decline
ErrorString += "Address Verification System (AVS) " +
"returned the following error: ";
switch (ReturnValues[5].Trim(char.Parse("|")))
{
case "A":
ErrorString += " the zip code entered does not match the billing address.";
break;
case "B":
ErrorString += " no information was provided for the AVS check.";
break;
case "E":
ErrorString += " a general error occurred in the AVS system.";
break;
case "G":
ErrorString += " the credit card was issued by a non-US bank.";
break;
case "N":
ErrorString += " neither the entered street address nor zip code matches the billing address.";
break;
case "P":
ErrorString += " AVS is not applicable for this transaction.";
break;
case "R":
ErrorString += " please retry the transaction; the AVS system was unavailable or timed out.";
break;
case "S":
ErrorString += " the AVS service is not supported by your credit card issuer.";
break;
case "U":
ErrorString += " address information is unavailable for the credit card.";
break;
case "W":
ErrorString += " the 9 digit zip code matches, but the street address does not.";
break;
case "Z":
ErrorString += " the zip code matches, but the address does not.";
break;
}
}
}
var tCompRespFail = new Tuple<string, string, string>(ReturnValues[6].ToString(), ErrorString, string.Join(",", ReturnValues));
return tCompRespFail;
}
CIM CODE (Tokanisation (Card not present method)
public Tuple<string, string, string> CreateTransaction(long profile_id, long payment_profile_id, decimal amt, string DDD)
{
CustomerProfileWS.ProfileTransAuthCaptureType auth_capture = new CustomerProfileWS.ProfileTransAuthCaptureType();
auth_capture.customerProfileId = profile_id;
auth_capture.customerPaymentProfileId = payment_profile_id;
auth_capture.amount = amt;//1.00m;
auth_capture.order = new CustomerProfileWS.OrderExType();
POSLib.POSManager objManager = new POSLib.POSManager();
auth_capture.order.invoiceNumber = objManager.GetTimestamp(DateTime.Now);
DateTime now = DateTime.Now;
auth_capture.order.description = "Service " + DDD;
CustomerProfileWS.ProfileTransactionType trans = new CustomerProfileWS.ProfileTransactionType();
trans.Item = auth_capture;
CustomerProfileWS.CreateCustomerProfileTransactionResponseType response = SoapAPIUtilities.Service.CreateCustomerProfileTransaction(SoapAPIUtilities.MerchantAuthentication, trans, null);
string AuthTranMsg = "";
string AuthTranCode = "";
for (int i = 0; i < response.messages.Length; i++)
{
AuthTranMsg = response.messages[i].text; // To Get Message n for loop to check the [i] is not empty
}
for (int i = 0; i < response.messages.Length; i++)
{
AuthTranCode = response.messages[i].code; // To Get Code n for loop to check the [i] is not empty
}
var tCompResp = new Tuple<string, string, string>(AuthTranCode, AuthTranMsg, response.directResponse);
return tCompResp;
}

Resources