Monday, February 18, 2008

Paypal NVP API example in C# (

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.

- 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

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 = "";
string strPassword = "XXXCCGUJP2EXXXX";
string strSignature = "XXXXXXZLVYanEw944w0oPBsJXXXXXXX";
string strCredentials = "USER=" + strUsername + "&PWD=" + strPassword + "&SIGNATURE=" + strSignature;

string strNVPSandboxServer = "";
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 +
"&STREET=" + addressTextbox.Text +
"&CITY=" + cityTextbox.Text +
"&STATE=" + regionTextbox.Text +
"&COUNTRY=" + countryDropDown.Text +
"&ZIP=95110" + postalTextbox.Text +
"&VERSION=" + strAPIVersion;

//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());

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

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

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;
string strErr = "Error: " + htResponse["L_LONGMESSAGE0"].ToString();
string strErrcode = "Error code: " + htResponse["L_ERRORCODE0"].ToString();
errLabel.Text = strErr;
errcodeLabel.Text = strErrcode;
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


Anonymous said...


I have the same code written in 2.0( Shall i post it here?


Anonymous said...

I would love to have it a version.


Unknown said... version is here:

Unknown 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.

Unknown 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.

Mahesh Tryambake said...

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

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
how do i connect to the webservice?

KidCoder said...


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, but since it uses signature-based authentication, 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 Merritt 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.
Please send me. Thank you.

Vipul said...
This comment has been removed by the author.
Vipul said...

Delete Comment From: Brad Oyler's Blog

Blogger Vipul said...

Please help.
I am not getting "ACK" key in htResponse. also i am getting multiple keys error.

Unknown said...


I am getting an error about:

Error code: 10002 Error: Security header is not valid.

Please help me here.


Unknown said...

Dhaha, it's most likely something with your API credentials. I beleive I got this error when trying to use my sandbox account but it was not activated. Cheers!

Eddie said...

Hi there. I wonder if you know where I can find those three dll files.

using com.paypal.sdk.profiles;
using com.paypal.sdk.util;

I found a perfect sample code from paypal, but I cannot find those files.

Here is the link for the sample code

Unknown said...

I am getting following error
why? can anybody help me?

Timeout processing request
Error code: 10001


Andolasoft said...

I like to introduce with my new site.
Are you interested?

Anonymous said...


How can i do recrring payment on this method.

I added following parameters

"&PROFILESTARTDATE=" + DateTime.Now.Date.ToString("yyyy-MM-ddT00:00:00") +

and change method name CreateRecurringPaymentsProfile
("&METHOD=CreateRecurringPaymentsProfile") in query string

But it show error code 10001.


Anonymous said...

hi Friend,

After googling i find solution

Recurring payment
use the foling PDF link and read CreateRecurringPaymentsProfile API

Anonymous said...

I am unable to find cvv2 number from paypal sandbox buyer account.

When I execute it sends error 10002

Best International Finance Books said...


Please post a valid test credit card no. with details like First Name, Last Name, CVV@, EXP Date etc.

Thanks in advance !!

Jon said...

Brilliant! I've been banging my head against Paypal's voluminous but not particularly helpful documentation for hours. Your concise code sample has stopped me hating the world, so thanks.

Anonymous said...

See full source code on PayPal API C# .Net Wrapper

Unknown said...

Convert your VB programs to C# with over 99% accuracy with the VBConversions VB.Net to C# Converter, the most accurate VB.Net to C# Converter available. Free download available at

convert to c#