Authorize.Net Integration using C# / ASP.NET
Call the function below to make a payment using Authorize.Net’s Advanced Integration Method (AIM).
private bool AuthorizePayment(string FirstName, string LastName, string Address, string City, string State, string ZIP, string Country, double Amount) { string AuthNetVersion = "3.1"; // Contains CCV support string AuthNetLoginID = "YourLoginID"; string AuthNetPassword = "YourPassword"; // Get this from your authorize.net merchant interface string AuthNetTransKey = "YourTransactionKey";WebClient objRequest = new WebClient(); System.Collections.Specialized.NameValueCollection objInf = new System.Collections.Specialized.NameValueCollection(30); System.Collections.Specialized.NameValueCollection objRetInf = new System.Collections.Specialized.NameValueCollection(30); byte[] objRetBytes; string[] objRetVals; string strError;objInf.Add("x_version", AuthNetVersion); objInf.Add("x_delim_data", "True"); objInf.Add("x_login", AuthNetLoginID); objInf.Add("x_password", AuthNetPassword); objInf.Add("x_tran_key", AuthNetTransKey); objInf.Add("x_relay_response", "False");// Switch this to False once you go live objInf.Add("x_test_request", "True");objInf.Add("x_delim_char", ","); objInf.Add("x_encap_char", "|");// Billing Address objInf.Add("x_first_name", FirstName); objInf.Add("x_last_name", LastName); objInf.Add("x_address", Address); objInf.Add("x_city", City); objInf.Add("x_state", State); objInf.Add("x_zip", ZIP); objInf.Add("x_country", Country);objInf.Add("x_description", "Description of Order");// Card Details objInf.Add("x_card_num", "4111111111111111"); objInf.Add("x_exp_date", "01/06");// Authorisation code of the card (CCV) objInf.Add("x_card_code", "123");objInf.Add("x_method", "CC"); objInf.Add("x_type", "AUTH_CAPTURE"); objInf.Add("x_amount", Amount.ToString());// Currency setting. Check the guide for other supported currencies objInf.Add("x_currency_code", "USD");try { // Pure Test Server objRequest.BaseAddress = "https://certification.authorize.net/gateway/transact.dll";// Actual Server //(uncomment the following line and also set above Testmode=off to go live) //objRequest.BaseAddress = // "https://secure.authorize.net/gateway/transact.dll";objRetBytes = objRequest.UploadValues(objRequest.BaseAddress, "POST", objInf); objRetVals = System.Text.Encoding.ASCII.GetString(objRetBytes).Split(",".ToCharArray());if (objRetVals[0].Trim(char.Parse("|")) == "1") { // Returned Authorisation Code this.lblAuthNetCode.Text = objRetVals[4].Trim(char.Parse("|")); // Returned Transaction ID this.lblAuthNetTransID.Text = objRetVals[6].Trim(char.Parse("|"));return true; } else { // Error! strError = objRetVals[3].Trim(char.Parse("|")) + " (" + objRetVals[2].Trim(char.Parse("|")) + ")";if (objRetVals[2].Trim(char.Parse("|")) == "44") { // CCV transaction decline strError += "Our Card Code Verification (CCV) returned " + "the following error: ";switch (objRetVals[38].Trim(char.Parse("|"))) { case "N": strError += "Card Code does not match."; break; case "P": strError += "Card Code was not processed."; break; case "S": strError += "Card Code should be on card but was not indicated."; break; case "U": strError += "Issuer was not certified for Card Code."; break; } }if (objRetVals[2].Trim(char.Parse("|")) == "45") { if (strError.Length>1) strError += "<br />n";// AVS transaction decline strError += "Our Address Verification System (AVS) " + "returned the following error: ";switch (objRetVals[5].Trim(char.Parse("|"))) { case "A": strError += " the zip code entered does not match " + "the billing address."; break; case "B": strError += " no information was provided for the AVS check."; break; case "E": strError += " a general error occurred in the AVS system."; break; case "G": strError += " the credit card was issued by a non-US bank."; break; case "N": strError += " neither the entered street address nor zip " + "code matches the billing address."; break; case "P": strError += " AVS is not applicable for this transaction."; break; case "R": strError += " please retry the transaction; the AVS system " + "was unavailable or timed out."; break; case "S": strError += " the AVS service is not supported by your " + "credit card issuer."; break; case "U": strError += " address information is unavailable for the " + "credit card."; break; case "W": strError += " the 9 digit zip code matches, but the " + "street address does not."; break; case "Z": strError += " the zip code matches, but the address does not."; break; } }// strError contains the actual error lblMsg1.Text = strError; return false; } } catch (Exception ex) { lblMsg1.Text = ex.Message; return false; } }
Works well for me. You will need to tweak a few parameters in order to make it work for you but I suppose there isn’t much for you to change.
Note: If you get an error like “The underlying connection was closed: Unable to connect to the remote server.” it most probably has to do with your Internet Connectivity — a firewall or something that’s blocking the request. If this happens to you, try the code on your hosting server and it should all work fine.


hai….
ur code is great….for last two days i was searching and searching in the web 4 this code…thanks….
but now i’m testing my progm an dits showing an error…“The merchant login ID or password is invalid or the account is inactive. (13)”
i’m working on test code,then y????can u help me….
// Pure Test Server
objRequest.BaseAddress =
“https://certification.authorize.net/gateway/transact.dll”;
i don’t know how to fix this error PLEASE help …
CS0246: The type or namespace name ‘WebClient’ could not be found (are you missing a using directive or an assembly reference?)
[sample code removed]
Mark: You need to import the System.Net namespace…
Asha: It means just what it says. Your userid seems to be inactive. authorize.net can help you better with that.
love you more than i can say!!!I found it for serveral days,the authorize.net doesn’t provide any program code ,thank you very much!…^&^
This looks great! Can’t wait to try it! I just got the PayPal code together, and now it’s time to implement the authorize.net code.
Thank you very much!
Looks great I have searched all over for this could I just use the AVS without charging the card ? using this code
+ im a .NET n00b I work in Clasic asp
I take it its like a func I just call it passing each variable like so:
call AuthorizePayment(StrFirstName, StrLatName ..
or am i way off lol
The merchant login ID or password is invalid or the account is inactive. (13)
is the only thing which stops me saying “This is great”
Ramesh: Check if you can access the merchant interface using your username/password details. If that’s successful, generate another Transaction Key and try again.
Awesome. Thanks so much!
Mikhail:
I had one question as to the return values in the objRetVals array. Do you have a list or a resource that names what the values in each position of the array are? I know some of them are self-explanatory but others are pretty nondescript.
Also, I was able to modify your code to work in vb.net, if you do any developing with vb let me know, and I will pass it along to you.
Brandon: I’ve sent you an email.
This is really great.
The code is working fine. I found it easy to modify the code to VB.Net.
One suggestion in the code you have used the webclient class this class uses the namespace system. Net.
Its better you specify below that we need to import the namespace
system.Net.
I’m I correct saying when we submit the transaction in Test Mode we need not submit the transaction key but once transaction set to Live Mode it is mandatory that we submit the Transaction Key
Anybody (Brandon) have the VB Version of this script? It looks great! Can’t wait to implement it-Thanks soooo much for posting!!!
this great i m searching from last two day ..
now got
thanks
ishaan
hai u r great i am very happy to this code of payment gateway
First of all, this code is awesome. (and by awesome I mean totally sweet).
How to test errors. (paraphrased from the doc)
To generate a specific error, set to test mode, and submit a transaction with the card number 4222222222222. Whatever the amount is will be the
error returned. If the amount you submit is 27.00, the system will return error #27.
I am having a bit of trouble understanding the handling of the errors. When we force a specific error, the message handling is not being used. Any hints?
Derek: objRetVals is what you need to look closely into. A specific error can be handled. Do use the authorize.net guide to see exactly which values they return. You will also get the order they come in and can use this to handle a specific error.
I understand a bit of the ogjRetVals. I am trying to understand what the [6] and [39] are in the following:
switch (objRetVals38.Trim(char.Parse(”|”)))
switch (objRetVals6.Trim(char.Parse(”|”)))
I assume they are position in the response from the Gateway API. In the documentation the ………
While looking once again at the code, it suddenly clicked. Thanks man, this is awesome.
I strongrly feel saying a simple thank you is not enough.
But that is all I can do for your this post.
Real cool work.
Applauses
Very nice solution. Dovetailed nicely into a payment processing web service.
Thanks! Saved me time, worked right out of the box.
Thank you for you incredible generosity for sharing this with the public!
Your A+ !!
convert this application to vb.net using this link
http://www.ragingsmurf.com/vbcsharpconverter.aspx
http://authors.aspalliance.com/aldotnet/examples/translate.aspx
Thanks Mikhail Esteves for awsome . This is really a piece of cake.
awesome code, except IE messed up some of your “code”. Of course it was all there in FireFox. You should offer to sell it to Authorize.net, as their how to code sucked!!!
Excellent! Took only a few minutes. Thanks!
I have found the detailed description of this stuff. If someone needs it refer to http://www.authorize.net/support/AIM_guide.pdf
Hi,
Your code segments are great. I guess this can solve the problems for the people like me.
Thanks once again,
Somu
Hi,
IMPORTANT BUG DETECTED
This code was a nice time saver for us. Thanks! One important bug I found is that when the customer’s address contains a “,” the objRetVals will actually wind up splitting the address up into TWO separate array indexes. If the address doesn’t have a comma, the whole address goes into objRetVals16, but if it does have a comma everything before the comma goes to objRetVals16 and everything after the comma goes to objRetVals17. This of course pushes all the other fields back an index.
The above code checks objRetVals38 for the Card Code Response Code, but of course this only works without a comma in the address. Hope this helps,
Josh
Hi asha,
change https://certification.authorize.net/gateway/transact.dll to “https://test.authorize.net/gateway/transact.dll”
It will work i believe.
Mani
Thanks so much for publishing this! I am working on expanding the code and making it a bit more flexible, and this code gave me a great head start! You can find my version (with credit to the Jackol’s Den, of course) at http://www.developingfor.net/miscellaneous/authorizenet-c-code.html
Thanks for this great contribution!
I just wanted to update this thread: I finally published the release version of my code based on this post at http://www.developingfor.net/free-code/authorizenet-code-release.html
Thanks again for the inspiration, I hope some people find it helpful.
Man…. You’re a life saver,
but note also that the value of “x_login” is the API Login value (this is different from the merchants login name), then the “x_password” value is not really neccessary…. I commented out this variable and supplied the API Login Variable, and I was good to go.
You rock. thanks for allowing me to spend time with my wife. God Bless You!
I modified the code to have it in a dll and it now accepts a struct and returns a struct. But that was all the work I had to do.
Thank you Thank you Thank you.