Monday, February 18, 2008

Paypal NVP API example in C# (asp.net)

This API is a very easy way to accept credit cards through your web app. Although , I don't think there are any simple examples available for ASP.Net 2.0. This beginner example will at least allow you to send a request to paypal and then get the response back from the API and display the error to a label.

Prereqs:
- Paypal business account with paypal websites pro enabled
- Paypal sandbox account (you must login and accept the agreement for websites pro from this account)
- get an API username, password, & signature from your sandbox account

Steps:
1- create an ASPX form with the following fields:
cctypeDdl, ccnumberTextbox, expdateDropDown, yearDropDown, CVVcodeTextBox, amountTextBox, firstnameTextbox, lastnameTextbox, addressTextbox, cityTextbox, regionTextbox, countryDropDown, postalTextbox
and these labels: successLabel, errLabel, errcodeLabel

2- Create a button control and button_click event handler

3- copy below code into your event handler

//API Credentials (3-token)
string strUsername = "brad_apiX.w3XXXXX.com";
string strPassword = "XXXCCGUJP2EXXXX";
string strSignature = "XXXXXXZLVYanEw944w0oPBsJXXXXXXX";
string strCredentials = "USER=" + strUsername + "&PWD=" + strPassword + "&SIGNATURE=" + strSignature;

string strNVPSandboxServer = "https://api-3t.sandbox.paypal.com/nvp";
string strAPIVersion = "2.3";

string strNVP = strCredentials + "&METHOD=DoDirectPayment" +
"&CREDITCARDTYPE=" + cctypeDdl.Text +
"&ACCT=" + ccnumberTextbox.Text +
"&EXPDATE=" + expdateDropDown.Text + yearDropDown.Text +
"&CVV2=" + CVVcodeTextBox.Text +
"&AMT=" + amountTextBox.Text +
"&FIRSTNAME=" + firstnameTextbox.Text +
"&LASTNAME=" + lastnameTextbox.Text +
"&IPADDRESS=255.55.167.002" +
"&STREET=" + addressTextbox.Text +
"&CITY=" + cityTextbox.Text +
"&STATE=" + regionTextbox.Text +
"&COUNTRY=" + countryDropDown.Text +
"&ZIP=95110" + postalTextbox.Text +
"&COUNTRYCODE=US" +
"&PAYMENTACTION=Sale" +
"&VERSION=" + strAPIVersion;

try
{
//Create web request and web response objects, make sure you using the correct server (sandbox/live)
HttpWebRequest wrWebRequest = (HttpWebRequest)WebRequest.Create(strNVPSandboxServer);
wrWebRequest.Method = "POST";
StreamWriter requestWriter = new StreamWriter(wrWebRequest.GetRequestStream());
requestWriter.Write(strNVP);
requestWriter.Close();

// Get the response.
HttpWebResponse hwrWebResponse = (HttpWebResponse)wrWebRequest.GetResponse();
StreamReader responseReader = new StreamReader(wrWebRequest.GetResponse().GetResponseStream());

//and read the response
string responseData = responseReader.ReadToEnd();
responseReader.Close();

string result = Server.UrlDecode(responseData);

string[] arrResult = result.Split('&');
Hashtable htResponse = new Hashtable();
string[] responseItemArray;
foreach (string responseItem in arrResult)
{
responseItemArray = responseItem.Split('=');
htResponse.Add(responseItemArray[0], responseItemArray[1]);
}

string strAck = htResponse["ACK"].ToString();

if (strAck == "Success" || strAck == "SuccessWithWarning")
{
string strAmt = htResponse["AMT"].ToString();
string strCcy = htResponse["CURRENCYCODE"].ToString();
string strTransactionID = htResponse["TRANSACTIONID"].ToString();
ordersDataSource.InsertParameters["TransactionID"].DefaultValue = strTransactionID;

string strSuccess = "Thank you, your order for: $" + strAmt + " " + strCcy + " has been processed.";
successLabel.Text = strSuccess;
}
else
{
string strErr = "Error: " + htResponse["L_LONGMESSAGE0"].ToString();
string strErrcode = "Error code: " + htResponse["L_ERRORCODE0"].ToString();
errLabel.Text = strErr;
errcodeLabel.Text = strErrcode;
return;
}
}
catch (Exception ex)
{
// do something to catch the error, like write to a log file.
Response.Write("error processing");
}

Keep in mind that you'll need to serve this page via SSL for production use. Otherwise, someone could sniff all your customers credit card numbers. For a inexpensive SSL certs, try godaddy.com

14 comments:

Anonymous said...

Hi,

I have the same code written in asp.net 2.0(VB.net). Shall i post it here?

Vips

Anonymous said...

I would love to have it a vb.net version.

Thanks!

Brad Oyler said...

vb.net version is here:
http://bradoyler.blogspot.com/2008/03/paypal-nvp-api-example-for-vbnet-aspnet.html

Ozzie said...

thanx for posting that example. you uncombobulated the spaghetti that paypal makes of its api for me. would you happen to know if it's possible to do something like that for recurring payments? i'm totally stuck on how to get recurring payments going with Direct Payment! anyway, thanks again. i'm using c# btw.

E2D said...

Is it possible to do this for Website Payments Standard? How can this be done?
When I'm trying the same for Standard, the error I'm getting is "Merchant account not defined correctly" or something like that.

Brad Oyler said...

I wasn't planning on handling recurring payment, but I may post code to void\credit a transaction with this API.
Also, you need Website Payments Pro to handle credit cards.

Popup said...

hi ,
Can u give me total code for Paypal for live site.
Thanks.

Ashrith said...

im a newbie.
i have this code, but cant use it.
where can i get the supporting files for ASP.NET 2.0(C# or VB.net)
how do i connect to the webservice?
PLEASE PLEASE PLEASE.....help me

KidCoder said...

Hi,

I tried to use some code based on this, but the wrWebRequest.GetResponse() call fails with the following exception:
System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel.
Do I need to attach a certificate or configure something differently?

KidCoder said...

Nevermind, I found what the problem was. My code POSTed to https://api.sandbox.paypal.com/nvp, but since it uses signature-based authentication, https://api-3t.sandbox.paypal.com/nvp is the correct URL.

Chandru said...

Thank you very much... it helps me a lot..

Otis said...

Wow, I just had a quick question about this, Do you need to be logged into your paypal sandbox account then try to connect to get a response.

Rod said...

what is the server url to go live?

Anonymous said...

Anyone, Who the people has the Paypal API sample for asp?! Thanks a lot.

benson_bn@youler.com
Please send me. Thank you.