18 October 2004

Authorize.Net Integration using C# / ASP.NET

Posted by Mikhail Esteves under: C#; Tips .

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.



31 Comments so far...

asha Says:

11 November 2004 at 11:50 am.

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”;

Mark Says:

27 November 2004 at 3:13 am.

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]

Mikhail Says:

29 November 2004 at 3:34 am.

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.

hao xu Says:

4 December 2004 at 2:31 pm.

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!…^&^

Svein Erik Says:

6 December 2004 at 6:38 pm.

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!

Skip Says:

18 January 2005 at 1:51 am.

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

ramesh chandra Says:

21 January 2005 at 5:33 pm.

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”

Mikhail Says:

22 January 2005 at 5:55 pm.

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.

Greg Thatcher Says:

8 March 2005 at 12:01 am.

Awesome. Thanks so much!

Brandon Says:

4 May 2005 at 6:46 pm.

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.

Mikhail Esteves Says:

9 May 2005 at 6:44 pm.

Brandon: I’ve sent you an email.

Kiran Says:

12 May 2005 at 2:02 pm.

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

Lon Says:

29 June 2005 at 12:10 pm.

Anybody (Brandon) have the VB Version of this script? It looks great! Can’t wait to implement it-Thanks soooo much for posting!!!

v george Says:

6 July 2005 at 11:19 am.

this great i m searching from last two day ..
now got
thanks
ishaan

atul tyagi Says:

6 July 2005 at 11:28 am.

hai u r great i am very happy to this code of payment gateway

Duncan Says:

9 July 2005 at 7:24 am.

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.

Derek Bruyere Says:

2 August 2005 at 12:07 am.

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?

Mikhail Esteves Says:

2 August 2005 at 12:33 am.

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.

Anonymous Says:

2 August 2005 at 11:38 am.

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.

Alok Tibrewal Says:

7 October 2005 at 4:20 pm.

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

Jared Nielsen Says:

21 October 2005 at 3:06 am.

Very nice solution. Dovetailed nicely into a payment processing web service.

ben Says:

28 January 2006 at 8:20 pm.

Thanks! Saved me time, worked right out of the box.

Dave Says:

20 March 2006 at 9:34 am.

Thank you for you incredible generosity for sharing this with the public!

Your A+ !!

joji Says:

3 April 2006 at 11:11 pm.

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.

Paul Says:

22 June 2006 at 10:09 am.

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!!!

Greg Harris Says:

10 March 2007 at 9:30 pm.

Excellent! Took only a few minutes. Thanks!

Artem Liman Says:

26 April 2007 at 8:54 pm.

I have found the detailed description of this stuff. If someone needs it refer to http://www.authorize.net/support/AIM_guide.pdf

Somu Says:

23 May 2007 at 10:31 am.

Hi,

Your code segments are great. I guess this can solve the problems for the people like me.

Thanks once again,

Somu

Josh Padnick Says:

9 July 2007 at 11:10 am.

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

Mani Says:

13 November 2007 at 5:49 pm.

Hi asha,
change https://certification.authorize.net/gateway/transact.dll to “https://test.authorize.net/gateway/transact.dll”

It will work i believe.

Mani

Joel Cochran Says:

13 February 2008 at 7:49 pm.

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!

Leave a Reply

Browse

Photography

Projects

Pages

Calendar

October 2004
M T W T F S S
« Sep   Nov »
 123
45678910
11121314151617
18192021222324
25262728293031

Categories

www.flickr.com

Use OpenDNS