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

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

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.

Dhanashree said...

HI,

I am getting an error about:

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

Please help me here.

Thanks,
Dhana

Brad Oyler 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.services;
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

https://cms.paypal.com/cms_content/US/en_US/files/developer/nvp_DoDirectPayment_cs.txt

Mohammed said...

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

Timeout processing request
Error code: 10001

Regards
Jam

Andolasoft said...

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

Anonymous said...

hi,

How can i do recrring payment on this method.

I added following parameters

"&PROFILESTARTDATE=" + DateTime.Now.Date.ToString("yyyy-MM-ddT00:00:00") +
"&BILLINGPERIOD=3" +
"&BILLINGFREQUENCY=Daily" +
"&INITAMT=2.00";

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

But it show error code 10001.

Thx

Anonymous said...

hi Friend,

After googling i find solution

Recurring payment
use the foling PDF link and read CreateRecurringPaymentsProfile API
parameters

https://cms.paypal.com/cms_content/US/en_US/files/developer/PP_NVPAPI_DeveloperGuide.pdf

Anonymous said...

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

When I execute it sends error 10002

Sunny said...

Hi,

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

zeniya opi 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 www.vbconversions.com

convert vb.net to c#