PayPal Direct Payment for C# developers

PayPal integration allows ASP.NET developers to create a Payment Data Transfer (PDT) via PayPal API express checkout to allow direct payments. PayPal Sandbox is a test account which will allow developers to test such API in order to avoid actual payments and transaction fees or interests.

Creating a sandbox account:

STEP 1. To create a new developers PayPal account, visit and click the orange Sign Up Now button as shown below:

STEP 2. Once you enter all your ACTUAL DETAILS from the register page, it is time to create a Sandbox Test Account. For a test account it is most suggested to create a Preconfigured Test Account. The figure below shows you how and where this option is available. This option will load a register form for the test account with information detail already in place. Simply copy the password and save it somewhere safe and proceed with the creation of account.

STEP 3. When an account is already available, you may either create more test accounts or login to an already existent one by selecting the right radio button and click Enter Sandbox Test Site.

STEP 4. The above step will take you to another part of the PayPal’s developers website, where you are requested to enter your login details. The email should be already written for you and even if it is not a correct existent account, simply write/paste the password given in the preconfigured test account and Login. Once logged in, you will be redirected to the PayPal Test Site as shown below:

STEP 5. Save the API settings of the test account created to use them in your project. To access your API credentials, you need to select “API Credentials” from the side menu of the SandBox account when logging in as indicated in step 2 and 3. Below is an image of what the credentials should look like. If you have no credentials it means something must have went wrong when creating the Preconfigured test account (make sure you that “Add Bank Account” is set on “Yes” when created).

P.S Note that details have been made unreadable for this article purposes.

In C# / .NET project:



In the Constants Class copy and modify as instructed the code below:

/// <summary>
/// Summary description for Constants.
/// </summary>
public class Constants

public const string ENVIRONMENT = “sandbox”;
public const string PAYPAL_URL = “;;
public const string ECURLLOGIN = “;;
public const string SUBJECT = “”;

public const string PROFILE_KEY = “Profile”;
public const string PAYMENT_ACTION_PARAM = “paymentAction”;
public const string PAYMENT_TYPE_PARAM = “paymentType”;

//replace email with Test Account Email from step 5 above
public const string STANDARD_EMAIL_ADDRESS = ““;

public const string WEBSCR_URL = PAYPAL_URL + “/cgi-bin/webscr”;

///sandbox 3t credentials
public const string PRIVATE_KEY_PASSWORD = “”;

//replace username with the API Username from step 5 above
public const string API_USERNAME = ““;

//replace password with the API password from step 5 above
public const string API_PASSWORD = “1398568007“;

//replace signature with the API Signature from step 5 above
public const string API_SIGNATURE = “AQUtt7vuZCvSg-XJploSa.sHTYlpA3d09hxWWvhFXEok06.EZ7f51ZHV“;
public const string CERTIFICATE = “”;

//Permission //No need to change anything
public const string OAUTH_SIGNATURE = “”;
public const string OAUTH_TOKEN = “”;
public const string OAUTH_TIMESTAMP = “”;



In the SetProfile Class copy and paste exactly the code below:

public static IAPIProfile CreateAPIProfile(string apiUsername, string apiPassword, string signature, string CertificateFile_Cer, string PrivateKeyPassword_Cer, String stage, string subject, string oauth_Signature, string oauth_Token, string oauth_Timestamp)

IAPIProfile profile = ProfileFactory.createSignatureAPIProfile();
profile.APIUsername = apiUsername;
profile.APIPassword = apiPassword;
profile.Environment = stage;
profile.Subject = subject;
profile.APISignature = signature;
return profile;



In the Utils Class copy and paste exactly the code below:

public static string GenerateCreditCardNumber(string cardType)

int[] cc_number = new int[16];
int cc_len = 16;
int start = 0;
Random r = new Random();
switch (cardType)

case “Visa”:
cc_number[start++] = 4;
case “Discover”:

cc_number[start++] = 6;
cc_number[start++] = 0;
cc_number[start++] = 1;
cc_number[start++] = 1;

case “MasterCard”:

cc_number[start++] = 5;
cc_number[start++] = (int)Math.Floor(r.NextDouble() * 5) + 1;

case “Amex”:

cc_number = new int[15];
cc_number[start++] = 3;
cc_number[start++] = r.Next(2) == 1 ? 7 : 4 ;
cc_len = 15;


for (int i = start; i < (cc_len – 1); i++)
cc_number[i] = (int)Math.Floor(r.NextDouble() * 10);

int sum = 0;
for (int j = 0; j < (cc_len – 1); j++)

int digit = cc_number[j];
if ((j & 1) == (cc_len & 1)) digit *= 2;
if (digit > 9) digit -= 9;
sum += digit;


int[] check_digit = new int[]{0, 9, 8, 7, 6, 5, 4, 3, 2, 1};
cc_number[cc_len – 1] = check_digit[sum % 10];

string result = string.Empty;
foreach (int digit in cc_number)
result += digit;
return result;


public static string BuildResponse(object response,string header1,string header2)


NVPCodec decoder = new NVPCodec();
decoder= (NVPCodec)response;

string res=”<center>”;
if(header1!=null )

res=res+ “<font size=2 color=black face=Verdana><b>” +header1 + “</b></font>”;
res=res+ “<br>”;
res=res+ “<br>”;


res=res+ “<b>”+header2+”</b><br>”;

res=res+ “<br>”;

res=res+”<table width=400>”;

for (int i=0; i<decoder.Keys.Count;i++)

res=res+ “<tr><td> ” +decoder.Keys[i].ToString() +”:</td>”;
res=res+”<td>” +decoder.GetValues(i)[0] +”</td>”;


return res;

return “Requested action not allowed”;



Now it is time to create a payment button. So, create a button/link button and name it “PayButton” for instance. In the code behind we need to create a onclick event for the button, plus another two methods. Copy the code below and modify the purple text as appropriate to best suit your requirements.

Add the following references to the aspx page code behind:

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

using System.Web.Security;

Copy the following Methods:

protected void PayButton_Click(object sender, EventArgs e)


String Username = Session[“Username”].ToString();

Session[BLL.PayPal.Constants.PROFILE_KEY] = SetProfile.CreateAPIProfile(BLL.PayPal.Constants.API_USERNAME, BLL.PayPal.Constants.API_PASSWORD, BLL.PayPal.Constants.API_SIGNATURE, “”, “”, BLL.PayPal.Constants.ENVIRONMENT, BLL.PayPal.Constants.SUBJECT, BLL.PayPal.Constants.OAUTH_SIGNATURE, BLL.PayPal.Constants.OAUTH_TOKEN, BLL.PayPal.Constants.OAUTH_TIMESTAMP);

NVPCallerServices caller = new NVPCallerServices();
caller.APIProfile = (IAPIProfile)Session[BLL.PayPal.Constants.PROFILE_KEY];

NVPCodec encoder = new NVPCodec();
encoder[“METHOD”] = “DoDirectPayment”;
encoder[“PAYMENTACTION”] = “Sale”;
encoder[“AMT”] = txtAmount.Text; //Enter the amount required from a textbox or label
encoder[“CREDITCARDTYPE”] = creditCardType.SelectedItem.Value;  //credit card type from a drop down list
encoder[“ACCT”] = creditCardNumber.Value; //credit card number from a textbox entered by user
encoder[“EXPDATE”] = expdate_month.Value.ToString() + expdate_year.Value; //Expiry Date of credit card
encoder[“CVV2”] = cvv2Number.Value; //CVV number from credit card entered by user
encoder[“FIRSTNAME”] = firstName.Value; //User first name
encoder[“LASTNAME”] = lastName.Value; //User last name / surname
encoder[“STREET”] = address1.Value; // User Address … city, state, zip and country code below
encoder[“CITY”] = city.Value; // *
encoder[“STATE”] = state.Value// *
encoder[“ZIP”] = zip.Value// *
encoder[“COUNTRYCODE”] = “US“; // *
encoder[“CURRENCYCODE”] = lstCurrency.SelectedValue; //currency code of the user country

string pStrrequestforNvp = encoder.Encode();
string pStresponsenvp = caller.Call(pStrrequestforNvp);

NVPCodec decoder = new NVPCodec();

string strAck = decoder[“ACK”];
if (strAck != null && (strAck == “Success” || strAck == “SuccessWithWarning”))
//If the transaction is SUCCESSFUL
lbl_message.Text = “Payment Successful”;


lbl_message.Text = “Payment not successful”;


catch (Exception ex)

throw ex;



private void creditCardType_SelectedIndexChanged(object sender, System.EventArgs e)

creditCardNumber.Value = Util.GenerateCreditCardNumber(creditCardType.SelectedItem.Value);


public static IAPIProfile SessionProfile

return (IAPIProfile)HttpContext.Current.Session[PayPal.Constants.PROFILE_KEY];
HttpContext.Current.Session[PayPal.Constants.PROFILE_KEY] = value;


Read more about more variables to insert on payment and currency codes:

HTML Variables:

Currency Codes:

32 thoughts on “PayPal Direct Payment for C# developers

  1. Who would like a full sample project for Direct Payments and also PayPal Express checkout. Please reply with your email and I will forward you a zipped version. Thanks and hope this helps

  2. Hi, please send me full sample of code, i want to integrate paypal and credit card in my application. i have done all the step, there is alot of confusion in step 5, it’s not clear to me. please send me full sample code (i am doing in C#) my email is ******


  3. Hey nice information but me too need a working sample.. am not able to figure out how to do it.. please send me as well thanks in advance.. my id is pr*****

  4. I have done payment in sandbox using above code. Amount is added to seller account but amount was not deducted from buyer account.why?

    • Did you check transaction history in both accounts (buyer and seller)? Do you see any transactions in the buyers account?

      This is a strange chase since before adding amount to seller, paypal checks settings for buyer and only if all goes well it should add the money to the seller.

  5. Could you send me the working example. Some nice code here including credit card number validation. Cheers (email address is *****

  6. Please it’s argent , will you send me zip version of Pypal direct method integration , i.e Paypal Direct payment on my mail id…

    I have done with all sandbox buyer , seler account, also done with credential but i couldn’t get how to integrate it in mvc4 ?

  7. Hello I would appreciate if you send me zip version of Paypal direct method payment including credit card validation (Paypal Direct Payment) zip I gave my email. many thanks I appreciate if you send me via my email.

    Best Regards,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s