Home » C# Programming

PayPal Integration

Hi All,

I am in a process to develop an application which will enable paypal integration for fee processing and donation.

Technologies: C#, SQL 2008

Kindly give me a piece of demo application which will help me to develope the same faster.





2 Answers Found


Answer 1

Try the paypal forums. it does not look like you need help in C# features.

Answer 2

Thanks Sheng, for  your quick response.



Search for  PayPal Integration


Hi All,

I am in a process to develop an application which will enable paypal integration for fee processing and donation.

Technologies: C#, SQL 2008

Kindly give me a piece of demo application which will help me to develope the same faster.





   I having problem with paypal gateway integration. Coding working in my local it's good. But after hosting it's not working in the website. It shows some error like this

"<pre lang="vb">[IOException: Authentication failed because the remote party has closed the transport stream.]
   System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest) +1100890
   System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest) +178
   System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest) +107
   System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest) +248
   System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest) +130
   System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult) +85
   System.Net.TlsStream.CallProcessAuthentication(Object state) +47
   System.Threading.ExecutionContext.runTryCode(Object userData) +66
   System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData) +0
   System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) +166
   System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) +145
   System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result) +728
   System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size) +44
   System.Net.PooledStream.Write(Byte[] buffer, Int32 offset, Int32 size) +25
   System.Net.ConnectStream.WriteHeaders(Boolean async) +122
[WebException: The underlying connection was closed: An unexpected error occurred on a send.]
   System.Web.Services.Protocols.WebClientProtocol.GetWebResponse(WebRequest request) +314
   System.Web.Services.Protocols.HttpWebClientProtocol.GetWebResponse(WebRequest request) +4
   System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) +172
   SNPPayPal.com.paypal.sandbox.www.PayPalAPIAASoapBinding.SetExpressCheckout(SetExpressCheckoutReq SetExpressCheckoutReq) in D:\web\karthik\SNPPayPal\SNPPayPal\Web References\com.paypal.sandbox.www\Reference.cs:1453
   SNPPayPal.CheckOutExpress.Button1_Click(Object sender, EventArgs e) in D:\web\karthik\SNPPayPal\SNPPayPal\CheckOutExpress.aspx.cs:50
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +105
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +107
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1746</pre>"

   Please anybody help me........



can anyone tell me 

how would i integrate paypal API in silverlight application for both DirectCheckout and Express Checkout








Does anybody know if there is any SIlverlight Paypal integration sample/tutorial? 


Looking for some help with VSTSDB along with Continuous Integration best practices:

I'm trying to get our project up to speed with the features that VSTSDB has to offer. I have the x4 DBs we have building, datagenerating, and SQL unit testing--all fine from within VS 2010 dev box. I'm a bit of a newbie with MSBUILD (TFS Build) and having trouble with some of these steps from the build server.

What Works Now in NightlyBuild:

Build related app code. Build and Deploy x4 DBs to integration server.

On #2 I can comment out the <msbuild target="deploy"...> and do a DataGeneration plan correctly, when the target DB has already been Deployed. I need them both to run (Deploy and DGen), but this causes errors when doing both. I'm sure it has something to do with the order of things on TFSBuild.

I tried having the Test project with my SQL Unit Tests kick off the DGen, but the Tests also run before the "AfterDropBuild". AfterDropBuld has been the suggested target to do the <msbuild> calls for this operation. Maybe I am missing some msbuild contstraints. However, I'm avoiding writing any custom Targets.

What I need:

Build App Code (no problem) Build and Deploy the DBs (working currently with AlwaysCreateNewDatabase=true) Run my DataTransform Dgen plan on x1 DB (failing). Run my SQL tests in the Test project (??? failing).

TFSBuild.proj snippet:

 <Target Name="AfterDropBuild">   
  <!-- Cumulative DB Builds -->
  <MSBuild Targets="Deploy" BuildInParallel="False" Projects="c:\bw\App.MyCoOnline\NightlyBuild\Main\MyCo.Online.Database.SharedDb\MyCo.Online.Database.SharedDb.dbproj"
       Properties="Configuration=Debug;OutDir=$(DropLocation)\$(BuildNumber)\Release\;TargetConnectionString=$(TargetConnection);TargetDatabase=SharedDb_cume;AlwaysCreateNewDatabase=true;GenerateDropsIfNotInProject=True;BlockIncrementalDeploymentIfDataLoss=False;DeployToDatabase=True;IgnorePermissions=True" />  
  <MSBuild Targets="Deploy" BuildInParallel="False" Projects="c:\bw\App.MyCoOnline\NightlyBuild\Main\MyCo.Online.Database.RefDb\MyCo.Online.Database.RefDb.dbproj"
       Properties="Configuration=Debug;OutDir=$(DropLocation)\$(BuildNumber)\Release\;TargetConnectionString=$(TargetConnection);TargetDatabase=RefDb_cume;AlwaysCreateNewDatabase=true;GenerateDropsIfNotInProject=True;BlockIncrementalDeploymentIfDataLoss=False;DeployToDatabase=True;IgnorePermissions=True" />
  <MSBuild Targets="Deploy" BuildInParallel="False" Projects="c:\bw\App.MyCoOnline\NightlyBuild\Main\MyCo.Online.Database.Op_OLTP\MyCo.Online.Database.Op_OLTP.dbproj"
       Properties="Configuration=Debug;OutDir=$(DropLocation)\$(BuildNumber)\Release\;TargetConnectionString=$(TargetConnection);TargetDatabase=Testing_cume_OLTP;AlwaysCreateNewDatabase=true;GenerateDropsIfNotInProject=True;BlockIncrementalDeploymentIfDataLoss=False;DeployToDatabase=True;IgnorePermissions=True" />
  <MSBuild Targets="Deploy" BuildInParallel="False" Projects="c:\bw\App.MyCoOnline\NightlyBuild\Main\MyCo.Online.Database.Op_STAGING\MyCo.Online.Database.Op_STAGING.dbproj"
       Properties="Configuration=Debug;OutDir=$(DropLocation)\$(BuildNumber)\Release\;TargetConnectionString=$(TargetConnection);TargetDatabase=Testing_cume_STAGING;AlwaysCreateNewDatabase=true;GenerateDropsIfNotInProject=True;BlockIncrementalDeploymentIfDataLoss=False;DeployToDatabase=True;IgnorePermissions=True" />
  <!-- Commented out b/c not working when done together with cumulative DB build.
	<MSBuild Targets="DataGeneration" BuildInParallel="False"
       Properties="SourceFile=.\Data Generation Plans\Op_STAGING_LI10551.dgen;ConnectionString=$(TargetConnection);Verbose=true;PurgeTablesBeforePopulate=True;" />-->

Error I get when doing the DGen with the build:

Using "DataGeneratorTask" task from assembly "Microsoft.Data.Schema.Tasks, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a".
Task "DataGeneratorTask"
 Data Generator Execution Task
 Started loading the data generation plan.
 Finished loading the data generation plan.
 Target data store validation starting...
 Table [dbo].[CompleteProvider] does not exist.
 Table [dbo].[Configuration] does not exist.
 Table [dbo].[GoodClaimHistory] does not exist.
 Table [dbo].[LoadInstance] does not exist.
 Table [dbo].[OutliersHistory] does not exist.
 Table [dbo].[Patient] does not exist.
 Table [dbo].[PharmacyClaims] does not exist.
 Table [dbo].[PharmGoodClaimIDwork] does not exist.
 Table [dbo].[RowStatus] does not exist.
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\TeamData\Microsoft.Data.Schema.Common.targets(289,5): error : Error occurred during population. [c:\bw\App.CmtOnline\NightlyBuild\Main\Cmt.Online.Database.Model_STAGING\Cmt.Online.Database.Model_STAGING.dbproj]
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\TeamData\Microsoft.Data.Schema.Common.targets(289,5): DGen warning : Could not find output CompleteProviderID for generator Sequential data bound generator on column dbo.CompleteProvider.CompleteProviderID. [c:\bw\App.CmtOnline\NightlyBuild\Main\Cmt.Online.Database.Model_STAGING\Cmt.Online.Database.Model_STAGING.dbproj]

Perhaps this could all be triggered from the Test project, but I'd rather not.



 In my shopping website..... I had integrated Paypal. Using the Developer / SandBox Version I had already tested the site from my local machine. It is working fine.

But after uploading the files in shared web-Server, whenever I am trying to call the Paypal, then always it is showing me the following error......

The operation has timed out Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Net.WebException: The operation has timed out

Source Error:

Line 32:             End If
Line 33:         Catch ex As Exception
Line 34:             Throw ex
Line 35: 
Line 36:         Finally

Source File: D:\whb\Sites\29519\Web\expresscheckout.aspx.vb    Line: 34

Stack Trace:

[WebException: The operation has timed out]
   expresscheckout.expresscheckout_Load(Object sender, EventArgs e) in D:\whb\Sites\29519\Web\expresscheckout.aspx.vb:34
   System.Web.UI.Control.OnLoad(EventArgs e) +99
   System.Web.UI.Control.LoadRecursive() +50
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627

Can anybody help me in this regard ????

I'm trying to add a PayPal "Buy Now" button to my component's description.  However, the form's HTML is simply being escaped, meaning the actual HTML is appearing instead.  Are forms disallowed?  Is there anyway around this?


Hi All,

I am having a problem of integrating paypal with my site. All the process works great i.e., site successfully redirects to paypal and the users can successfully subscibe, but the problem is the "notify_Url" variable redirects the paypal to my site page but when I send a request from that page to validate the payment process the paypal always send the response as "Invalid". I am using a Subscribe button of paypal.




Has anyone integrated Paypal website payments standard into either the PostAd or Register.aspx?





Does anyone have any thoughts on how to interrupt the process of the below code so I can

insert a simple Paypal button with IPN without the process automatically finishing? Ideally

I'd like to replace the "Finish" button with the Paypal button.........

Thanks in Advance

Old Dave

<legend>For how long should this Ad be listed?</legend>
                                <asp:DropDownList ID="NumDaysList" Runat="server">
                                    <asp:ListItem Value="2">2 days</asp:ListItem>
                                    <asp:ListItem Value="7" Selected="True">7 days</asp:ListItem>
                                    <asp:ListItem Value="14">14 days</asp:ListItem>
                                    <asp:ListItem Value="21">21 days</asp:ListItem>
                                    <asp:ListItem Value="28">28 days</asp:ListItem>
                    <asp:WizardStep ID="WizardStep2" Runat="server" StepType="Complete" Title="Done">
                        <h2 class="section">
                        <div class="content_right">
                                Your Ad was successfully submitted. </p>
                            <p style="text-align: center">
                                <asp:HyperLink Runat="server" ID="UploadImagesLink" Font-Bold="True" NavigateUrl="ManagePhotos.aspx?id=">Upload Photos for your Ad now</asp:HyperLink>
                                <br />
                                    <asp:HyperLink Runat="server" ID="MyAdsLink" Font-Bold="True" NavigateUrl="~/MyAds.aspx">Go to My Ads page</asp:HyperLink>
                <StepStyle CssClass="wizard-step" />
                <NavigationStyle HorizontalAlign="Left" />
<script type="text/javascript">
    function textCounter(elem, maxLimit)
        if (elem.value.length > maxLimit)
            elem.value = elem.value.substring(0, maxLimit);









hi friends!

i am working on an ecommerce site based on "The Beerhouse" template.

i need to submit my shopping cart to paypal but only one item is submitted to the list of items.

i need to submit all the items which can be multiple items in a single cart.

i need to modify the code of the template to do this.

please help me.


Here is the code i use to integrate my .NET store with PayPal in C#. This will respond to Paypal IPN Update a transaction on your DB (you have to create a new table on your DB for the IPN variables and a new procedure to add the transaction in a ..\components\*.cs file) and sends you an email with the transaction. change the email address at the
bottom of the page that says "sales@yourdomain.com" to your sales sender address. you can also test it at www.eliteweaver.com. I copied and pasted this from my transaction file and the formatting has gone a bit wild but if you copy and paste it into a .net page it should be OK.

<%@ Page Language="C#" %>
<%@ import Namespace="System.Net" %>
<%@ import Namespace="System" %>
<%@ import Namespace="System.IO" %>
<%@ import Namespace="System.Web.Mail" %>
<script runat="server" >

String CmdString, objHttp, OrderID, Txn_id, Payment_status, Receiver_email, Item_name,
Item_number, Quantity, Invoice, Custom,
Payment_gross, Payer_email, Pending_reason, Payment_date, Payment_fee,
Txn_type, First_name, Last_name, Address_street, Address_city, Address_state,
Address_zip, Address_country, Address_status, Payer_status, Payer_id, Payment_type,
Notify_version, Verify_sign, Subscr_date, Period1, Period2, Period3,
Amount1, Amount2, Amount3, Recurring, Reattempt, Retry_at, Recur_times,
Username, Password, Subscr_id, response;

private void Page_Init(object sender, System.EventArgs e)
string stringPost = Request.Form.ToString();
// assign posted variables to local variables
Txn_id = Request.Form["txn_id"];
Receiver_email = Request.Form["receiver_email"];
Item_name = Request.Form["item_name"];
Item_number = Request.Form["item_number"];
Quantity = Request.Form["quantity"];
Invoice = Request.Form["invoice"];
Custom = Request.Form["custom"];
Payment_status = Request.Form["payment_status"];
Pending_reason = Request.Form["pending_reason"];
if(Payment_status != "Pending")
Pending_reason = " ";
Payment_date = Request.Form["payment_date"];
Payment_fee = Request.Form["payment_fee"];
Payment_gross = Request.Form["payment_gross"];
Txn_type = Request.Form["txn_type"];
First_name = Request.Form["first_name"];
Last_name = Request.Form["last_name"];
Address_street = Request.Form["address_street"];
Address_city = Request.Form["address_city"];
Address_state = Request.Form["address_state"];
Address_zip = Request.Form["address_zip"];
Address_country = Request.Form["address_country"];
Address_status = Request.Form["address_status"];
Payer_email = Request.Form["payer_email"];
Payer_status = Request.Form["payer_status"];
Payer_id = Request.Form["payer_id"];
Payment_type = Request.Form["payment_type"];
Notify_version = Request.Form["notify_version"];
Verify_sign = Request.Form["verify_sign"];

// post to paypal and await response : use: "https://www.paypal.com/cgi-bin/webscr" for real;
// use: "http://www.eliteweaver.co.uk/testing/ipntest.php" to test;

HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("https://www.paypal.com/cgi-bin/webscr");
httpWebRequest.Method = "POST";
// length plus 21 because &cmd=_notify-validate is 21 chars long
httpWebRequest.ContentLength = stringPost.Length + 21;
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
StreamWriter streamWriter = null;
streamWriter = new StreamWriter(httpWebRequest.GetRequestStream());
stringPost = stringPost + "&cmd=_notify-validate";
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
response = streamReader.ReadToEnd();

// Step 1c: Process the response from PayPal.
if (httpWebResponse.StatusCode != HttpStatusCode.OK )
// an error has occurred
MailUsTheOrder("Status Error: " + httpWebResponse.StatusCode);
switch (response)
// check for new version of paypal if different send notify email
case "VERIFIED":
if ( Notify_version != "1.4" )
MailMessage mailObj = new MailMessage();
mailObj.From = "CJC BodyCare";
mailObj.To = Receiver_email;
mailObj.Subject = "Paypal Version Change";
mailObj.Body = "I see a new version of PayPal Notify IPN Service!!! Go check the PayPal site for updates!" + '\n'
+ "I currently see version: " + Notify_version;
mailObj.BodyFormat = MailFormat.Html;
// still to do
// check that Txn_id has not been previously processed
// check that Receiver_email is an email address in your PayPal account
// process payment

// check that Payment_status=Completed
switch (Payment_status)
case "Completed": //The payment has been completed and the funds are successfully in your account balance

// Perform steps 2-5 above.
// Continue with automation processing if all steps succeeded.

if (Receiver_email == "sales@christopherjohnconnelly.com")
switch (Txn_type)
case "web_accept": //The payment was sent by your customer via the Web Accept feature.
case "cart": //This payment was sent by your customer via the Shopping Cart feature
MailUsTheOrder("PROCESS ME: The order was completed successfully.");
case "send_money": //This payment was sent by your customer from the PayPal website, using the "Send Money" tab
MailUsTheOrder("PROCESS ME: Somebody sent us money!");
case "subscr_signup": //This IPN is for a subscription sign-up
MailUsTheOrder("PROCESS ME: Subscription signup.");
case "subscr_cancel": //This IPN is for a subscription cancellation
MailUsTheOrder("PROCESS ME: Subscription cancellation.");
case "subscr_failed": //This IPN is for a subscription payment failure
MailUsTheOrder("FAILURE: Subscription failed.");
case "subscr_payment": //This IPN is for a subscription payment
MailUsTheOrder("COOL: We got cash!");
case "subscr_eot": //This IPN is for a subscription's end of term
MailUsTheOrder("WHAT IS THIS? Subscription end of term.");
switch (Address_status)
case "confirmed": //Customer provided a Confirmed Address
case "unconfirmed": //Customer provided an Unconfirmed Address
switch (Payer_status)
case "verified": //Customer has a Verified U.S. PayPal account
case "unverified": //Customer has an Unverified U.S. PayPal account
case "intl_verified": //Customer has a Verified International PayPal account
case "intl_unverified": //Customer has an Unverified International PayPal account
switch (Payment_type)
case "echeck": //This payment was funded with an eCheck
case "instant": //This payment was funded with PayPal balance, credit card, or Instant Transfer
MailUsTheOrder("WEIRD: Someone is notifying us that the payments were received by someone else???");
case "Pending": //The payment is pending - see the "pending reason" variable below for more information. Note: You will receive another instant payment notification when the payment becomes "completed", "failed", or "denied"
switch (Pending_reason)
case "echeck": // The payment is pending because it was made by an eCheck, which has not yet cleared
case "intl": //The payment is pending because you, the merchant, hold an international account and do not have a withdrawal mechanism. You must manually accept or deny this payment from your Account Overview
case "verify": //The payment is pending because you, the merchant, are not yet verified. You must verify your account before you can accept this payment
case "address": //The payment is pending because your customer did not include a confirmed shipping address and you, the merchant, have your Payment Receiving Preferences set such that you want to manually accept or deny each of these payments. To change your preference, go to the "Preferences" section of your "Profile"
case "upgrade": //The payment is pending because it was made via credit card and you, the merchant, must upgrade your account to Business or Premier status in order to receive the funds
case "unilateral": //The payment is pending because it was made to an email address that is not yet registered or confirmed
case "other": //The payment is pending for an "other" reason. For more information, contact customer service
MailUsTheOrder("PENDING: Order is waiting to be processed.");
case "Failed": //The payment has failed. This will only happen if the payment was made from your customer's bank account
MailUsTheOrder("FAILED: This only happens if the payment was made from our customer's bank account.");
case "Denied": //You, the merchant, denied the payment. This will only happen if the payment was previously pending due to one of the "pending reasons"
MailUsTheOrder("DENIED: We denied this payment.");
// add transaction to database
IBuySpy.TransactionDB TransactionSystem = new IBuySpy.TransactionDB();
TransactionSystem.AddTransaction( Txn_id, Receiver_email, Item_name, Item_number, Quantity, Invoice, Custom, Payment_status, Pending_reason, Payment_date, Payment_fee, Payment_gross, Txn_type, First_name, Last_name, Address_street, Address_city, Address_state, Address_zip, Address_country, Address_status, Payer_email, Payer_status, Payer_id, Payment_type, Notify_version, Verify_sign );
case "INVALID":
// Possible fraud. Log for investigation or an error
MailUsTheOrder("INVALID: Possible fraud. Log for investigation or an error");
// error
MailUsTheOrder("Default: error: Response is: " + response);
private void MailUsTheOrder(string TagMsg)
MailMessage mailObj = new MailMessage();
mailObj.From = "sales@yourdomain.com";
mailObj.Subject = TagMsg;
mailObj.Body = TagMsg + "<br>" + "<br>";
mailObj.To = Receiver_email;
mailObj.BodyFormat = MailFormat.Html;
mailObj.Priority = MailPriority.High;
mailObj.Body = mailObj.Body + "Order ID: " + OrderID + "<br>"
+ "Transaction ID: " + Txn_id + "<br>"
+ "Transaction Type:" + Txn_type + "<br>"
+ "Payment Type: " + Payment_type + "<br>"
+ "Payment Status: " + Payment_status + "<br>"
+ "Pending Reason: " + Pending_reason + "<br>"
+ "Payment Date: " + Payment_date + "<br>"
+ "Receiver Email: " + Receiver_email + "<br>"
+ "Invoice: " + Invoice + "<br>"
+ "Item Number: " + Item_number + "<br>"
+ "Item Name: " + Item_name + "<br>"
+ "Quantity: " + Quantity + "<br>"
+ "Custom: " + Custom + "<br>"
+ "Payment Gross: " + Payment_gross + "<br>"
+ "Payment Fee: " + Payment_fee + "<br>"
+ "Payer Email: " + Payer_email + "<br>"
+ "First Name: " + First_name + "<br>"
+ "Last Name: " + Last_name + "<br>"
+ "Street Address: " + Address_street + "<br>"
+ "City: " + Address_city + "<br>"
+ "State: " + Address_state + "<br>"
+ "Zip Code: " + Address_zip + "<br>"
+ "Country: " + Address_country + "<br>"
+ "Address Status: " + Address_status + "<br>"
+ "Payer Status: " + Payer_status + "<br>"
+ "Verify Sign: " + Verify_sign + "<br>"
+ "Subscriber Date: " + Subscr_date + "<br>"
+ "Period 1: " + Period1 + "<br>"
+ "Period 2: " + Period2 + "<br>"
+ "Period 3: " + Period3 + "<br>"
+ "Amount 1: " + Amount1 + "<br>"
+ "Amount 2: " + Amount2 + "<br>"
+ "Amount 3: " + Amount3 + "<br>"
+ "Recurring: " + Recurring + "<br>"
+ "Reattempt: " + Reattempt + "<br>"
+ "Retry At: " + Retry_at + "<br>"
+ "Recur Times: " + Recur_times + "<br>"
+ "UserName: " + Username + "<br>"
+ "Password: " + Password + "<br>"
+ "Subscriber ID: " + Subscr_id + "<br>"
+ "Notify Version: " + Notify_version + "<br>";





Integrating encrypted paypal buttons is a pain! Hopefully this helps.

Basically it is a 4 stage process. I have put it together from postings on other sites. None of this is my own work so I can't take credit for it but I'm putting it all here in one place to hopefully save you time.

The code is provided AS IS. It works for me but it may not work for you. I offer no guarantees and I am unable to offer any help with modifying it. I host my applications at maximumasp.com so I can tell you this works on their VPS servers (Gratuitous plug: Maximumasp are great and my refferal number is DSHD-6726).

The sites where I found this information are:


The p12 certificate

Download and install Win32 OpenSSL from Shining Light Productions. Then Create a private key: 
    openssl genrsa -out my-prvkey.pem 1024

Create a public cert using the private key:
    openssl req -new -key my-prvkey.pem -x509 -days 3650 -out my-pubcert.pem

Export the private key and public cert to PKCS#12 format:
    openssl pkcs12 -export -inkey my-prvkey.pem -in my-pubcert.pem -out mycert.p12

You will be prompted for creating a password when you export to PKCS#12 format. Remember the password. You will need the .p12 file and its password when you use this class.

If you are on a shared virtual hosting plan, you may need to contact your hosting company to get them to install the certificate on your server. Send them the .p12 certificate and it's password.

Upload your certificate to your PayPal account to get your "cert_id" for the code behind, download the PayPal certificate and put it in your App_Data folder, then block non encrypted payments. All here: https://www.paypal.com/IntegrationCenter/ic_button-encryption.html#step2


The Form

Add these variables between the form tags of your aspx page
<input type="hidden" name="cmd" value="_s-xclick">
<asp:Literal runat="server" id="strEncrypt" />

Add an asp button with the postback url set to either the sandbox or live paypal site
<asp:Button ID="btnPayPal" runat="server" Text="Pay with PayPal" PostBackUrl="https://www.sandbox.paypal.com/cgi-bin/webscr" />


The code behind

This encrypts your form variables and writes a hidden variable named "encrypted" to the literal "strEncrypt". Put this where it will be executed before the user can click "btnPayPal" (e.g. Page_Load).

Imports com.paypal.demo

Dim paypalCertPath AsString = Server.MapPath("~/App_Data/paypal_cert_pem.txt")
Dim signerPfxPath AsString = Server.MapPath("~/App_Data/mycert.p12")
Dim signerPfxPassword AsString = "mycert.p12 password"'testing only - get from secure place when live.
Dim clearText AsString = "cmd=_xclick" & vbLf & _
"business=you@yourbusiness.com" & vbLf & _
"currency_code=GBP" & vbLf & _
"item_name=Subscription" & vbLf & _
"amount=15.00" & vbLf & _
"no_shipping=2" & vbLf & _
"no_note=1" & vbLf & _
"return=https://www.yoursite.com/return.aspx" & vbLf & _
"cancel_return=https://www.yoursite.com/cancel.aspx" & vbLf & _
Dim ewp AsNew ButtonEncryption()
ewp.LoadSignerCredential(signerPfxPath, signerPfxPassword)
ewp.RecipientPublicCertPath = paypalCertPath
Dim result AsString = ewp.SignAndEncrypt(clearText)

strEncrypt.Text = "<input type=""hidden"" name=""encrypted"" value=""" & result & """ />"

The class

This class has been slightly modified from PayPal_HarryX's original to prevent a "System.Security.Cryptography.CryptographicException: The system cannot find the file specified" error. It has also been converted to VB. You can download the original C# version from PayPal_HarryX's post but you need to change:

_signerCert = new X509Certificate2(signerPfxCertPath, signerPfxCertPassword);


_signerCert = new X509Certificate2(File.ReadAllBytes(signerPfxCertPath), signerPfxCertPassword, X509KeyStorageFlags.MachineKeySet);

And add the namespaces
using system.IO
using System.Security.Cryptography.X509Certificates

Here is the original. And here is the fix.

Save this class in the App_Code folder of your application.

Here is the modified VB code.

Imports Microsoft.VisualBasic
Imports System
Imports System.Web
Imports System.Collections.Generic
Imports System.Text
Imports System.Security.Cryptography
Imports Pkcs = System.Security.Cryptography.Pkcs
Imports X509 = System.Security.Cryptography.X509Certificates
Imports System.Security.Cryptography.X509Certificates
Imports System.IO

Namespace com.paypal.demo

PublicClass ButtonEncryption
Private _encoding As Encoding = Encoding.[Default]
Private _recipientPublicCertPath AsString
Private _signerCert As X509.X509Certificate2
Private _recipientCert As X509.X509Certificate2



''' <summary>
''' Character encoding, e.g. UTF-8, Windows-1252
''' </summary>

PublicProperty Charset() AsString
Return _encoding.WebName
Set(ByVal value AsString)
If value IsNotNothingAndAlso value <> ""Then
_encoding = Encoding.GetEncoding(value)

''' <summary>
''' Path to the recipient's public certificate in PEM format
''' </summary>

PublicProperty RecipientPublicCertPath() AsString
Return _recipientPublicCertPath
Set(ByVal value AsString)
_recipientPublicCertPath = value
_recipientCert =
New X509.X509Certificate2(_recipientPublicCertPath)

''' <summary>
''' </summary>
''' <param name="signerPfxCertPath">File path to the signer's public certificate plus private key in PKCS#12 format</param>
''' <param name="signerPfxCertPassword">Password for signer's private key</param>

PublicSub LoadSignerCredential(ByVal signerPfxCertPath AsString, ByVal signerPfxCertPassword AsString)
_signerCert = New X509.X509Certificate2(File.ReadAllBytes(signerPfxCertPath), signerPfxCertPassword, X509KeyStorageFlags.MachineKeySet)
Catch ex As Exception
ThrowNew Exception("<b>Signer Cert Path: " & signerPfxCertPath & "</b><br><br>" & ex.ToString())

''' <summary>
''' Sign a message and encrypt it for the recipient.
''' </summary>
''' <param name="clearText">Name value pairs must be separated by \n (vbLf or Chr(10)), for example "cmd=_xclick\nbusiness=..."</param>
''' <returns></returns>

PublicFunction SignAndEncrypt(ByVal clearText AsString) AsString
Dim result AsString = Nothing
Dim messageBytes AsByte() = _encoding.GetBytes(clearText)
Dim signedBytes AsByte() = Sign(messageBytes)
Dim encryptedBytes AsByte() = Envelope(signedBytes)
result = Base64Encode(encryptedBytes)
Return result

PrivateFunction Sign(ByVal messageBytes AsByte()) AsByte()
Dim content AsNew Pkcs.ContentInfo(messageBytes)
Dim signed AsNew Pkcs.SignedCms(content)
Dim signer AsNew Pkcs.CmsSigner(_signerCert)
Dim signedBytes AsByte() = signed.Encode()
Return signedBytes

PrivateFunction Envelope(ByVal contentBytes AsByte()) AsByte()
Dim content AsNew Pkcs.ContentInfo(contentBytes)
Dim envMsg AsNew Pkcs.EnvelopedCms(content)
Dim recipient AsNew Pkcs.CmsRecipient(Pkcs.SubjectIdentifierType.IssuerAndSerialNumber, _recipientCert)
Dim encryptedBytes AsByte() = envMsg.Encode()
Return encryptedBytes

PrivateFunction Base64Encode(ByVal encoded AsByte()) AsString
Const PKCS7_HEADER AsString = "-----BEGIN PKCS7-----"
Const PKCS7_FOOTER AsString = "-----END PKCS7-----"
Dim base64 AsString = Convert.ToBase64String(encoded)
Dim formatted AsNew StringBuilder()
Return formatted.ToString()


Good Luck!

If this post was helpful to you, Please "Mark As Answer". 



Hello, I don't know the correct way to do the following:

Have a "Buy Now" button for a product on my websiteAllow the user to click the button, and be redirected to a login page on the PayPal website (not my own page so it has HTTPS).Have the user redirected back the page they were on before clicking the button.Have my website use IPN (Instant Payment Notification) to get a validation that the user successfully payed and allow them to download the product they payed for (in my case, software licenses).

I know that PayPal Merchant Services allows you to automatically generate buttons, but I want to be able to dynamically generate buttons programmatically in my code (onto a ASP Literal control).

Anyone have an articles or example code for this? Thanks in advance. 




I am trying to setup a service and as one of the payment schemes, I would like a user to be a able to pay an initial deposit and each time he/she uses the service, money will be deducted from the deposit. I am not sure if this is available through PayPal.

Please can someone point me to the right direction e.g. Paypal service or similar  options.


Many thanks



Hi all,

I've been using paypal for some time and I came across the PayPal SDK for ASP.NET. After a lot of searching I've reached the conclusion that this SDK is obsolete, and I was looking for some advice on a replacement, or if the SOAP API is worth the effort. Any advice on using PayPal with ASP.NET is welcome. I overcame the nested forms issue some time ago but I've forgotten how... 


Heloo all,

I have received alot of help from this site, and just wanted to post my solution to what seems to be an all too common problem. Hopefully this helps others.

My problem was trying to work around the nested form issue that seems to derive from using master pages. My solution is not very elegant (at all!) or utilize fancy coding, but it has worked for my simple needs. Keep in mind that my needs were simple:

1. I am using my own cart and simply needed to send a single item_name to PayPal which was the Order Number that my cart creates.

2. I am only sending a single amount to PayPal, and am not using the PayPal site to calculate shipping, discounts etc...

The first thing I did was to place the following input fields on my .aspx page WITHOUT the <form> tags that PayPal usually deems are necessary.





<inputtype="hidden"name="amount"value='<%=PayPalCartAmount()%>' /> 

Note that I am populating the values of the item_name and amount fields from code behind using functions similiar to below. (GetOrderNumber function resides in an external class while PayPalCartAmount resides in .aspx code behind)

Public Function PayPalCartAmount() As String
code for blah,blah,blah
        Return blah,blah,blah
    End Function


Finally I added the following button to the page to submit it all:

<asp:ImageButtonID="submit"runat="server"ImageUrl="/images/checkout-paypal.gif"  AlternateText="Purchase Using Paypal"PostBackUrl="https://www.paypal.com/us/cgi-bin/webscr"/>

I assume that this works because the <form> tags do in fact still exist when the master page and content page is rendered together upon page load? If someone with more experience could verify this I would appreciate it.

Thanks again and I hope this saves someone unnecessary headaches.


I have been searching for weeks trying to find a solution for this. I found one post similar on another forum from a few years ago, but no replies were ever made to it.

I have a site with a subscription service and I am using paypal to process the payments. Everything works correctly with processing the payment and I even get successful send/receive messages when looking at the IPN history in PayPal Sandbox. But for some reason, none of my messages are sent and the databases aren't updated.

I know the mail and db update code are correct as I am successfully using a copy of an application (free trial) to handle the IPN, but it does not support subscriptions, so I cannot process new subscription profiles, only the transactions. Both the sending of mail and updating the db records work in that app, but not in the one I build from the paypal sample.

Has anyone else had this problem or have any suggestions? The codebehind for the listener is below:

Thanks in advance!

FYI - asp.net 2.0 and sql server 2008 with 1and1 hosting

Imports System.Data.SqlClient
Imports System.Net
Imports System.IO
Imports System.Web.Mail
Imports System.Data
Imports System

Partial Class ABQipn
   Inherits System.Web.UI.Page
   Private CmdString As String, objHttp As String, Txn_id As String, Payment_status As String, Receiver_email As String, Custom As String, _
 Payment_gross As String, Payer_email As String, Payment_fee As String, Txn_type As String, _
 First_name As String, Last_name As String, Notify_version As String, Verify_sign As String

   Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
      ' assign posted variables to local variables
      Txn_id = Request.QueryString("txn_id")
      Payment_status = Request.QueryString("Payment_status")
      Receiver_email = Request.QueryString("Receiver_email")
      Custom = Request.QueryString("Custom")
      Payment_gross = Request.QueryString("Payment_gross")
      Payer_email = Request.QueryString("Payer_email")
      Payment_fee = Request.QueryString("Payment_fee")
      Txn_type = Request.QueryString("Txn_type")
      First_name = Request.QueryString("First_name")
      Last_name = Request.QueryString("Last_name")
      Notify_version = Request.QueryString("Notify_version")
      Verify_sign = Request.QueryString("Verify_sign")

      Dim strSandbox As String = "https://www.sandbox.paypal.com/cgi-bin/webscr"
      Dim strLive As String = "https://www.paypal.com/cgi-bin/webscr"
      Dim req As HttpWebRequest = CType(WebRequest.Create(strSandbox), HttpWebRequest)

      'Set values for the request back
      req.Method = "POST"
      req.ContentType = "application/x-www-form-urlencoded"
      Dim Param() As Byte = Request.BinaryRead(HttpContext.Current.Request.ContentLength)
      Dim strRequest As String = Encoding.ASCII.GetString(Param)
      strRequest = strRequest + "&cmd=_notify-validate"
      req.ContentLength = strRequest.Length

      ' post to paypal and await response : use: "https://www.paypal.com/cgi-bin/webscr" for real;
      Dim proxy As New WebProxy(New System.Uri("http://ntproxyus.lxa.perfora.net:3128"))
      req.Proxy = proxy

      'Send the request to PayPal and get the response
      Dim streamOut As StreamWriter = New StreamWriter(req.GetRequestStream(), Encoding.ASCII)
      Dim streamIn As StreamReader = New StreamReader(req.GetResponse().GetResponseStream())
      Dim strResponse As String = streamIn.ReadToEnd()

      ' Process the response from PayPal.

      Select Case Txn_type
         Case "subscr_signup"
            'This IPN is for a subscription sign-up
            MailUsTheItem("Ad Subscription Recieved")
            Exit Select
         Case "subscr_cancel"
            'This IPN is for a subscription cancellation
            MailUsTheItem("Ad Subscription Cancelled")
            Exit Select
         Case "subscr_failed"
            'This IPN is for a subscription payment failure
            MailUsTheItem("FAILURE: Subscription failed")
            Exit Select
         Case "subscr_payment"
            'This IPN is for a subscription payment
            MailUsTheItem("Ad Payment Recieved")
            Exit Select
         Case "subscr_eot"
            'This IPN is for a subscription's end of term
            MailUsTheItem("FAILURE: Subscription end of term")
            Exit Select
      End Select
   End Sub
   Sub MailUsTheItem(ByVal TagMsg As String)
      Dim objMM As New MailMessage()
      objMM.To = "christopher@christopherwhitson.com"
      objMM.From = "ads@abqfind.com"
      objMM.BodyFormat = MailFormat.Text
      objMM.Priority = MailPriority.High
      objMM.Subject = TagMsg
      objMM.Body = TagMsg & " on the ABQfind Website at " + DateTime.Now & vbCrLf & vbCrLf & _
                  "Ad Id: " + Custom & vbCrLf & _
                  "Txn_id: " + Txn_id & vbCrLf & _
                  "Payer Email: " + Payer_email & vbCrLf & _
                  "Last Name: " + Last_name & vbCrLf & _
                  "First Name: " + First_name & vbCrLf & _
      SmtpMail.SmtpServer = "smtp.1and1.com"
      objMM.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "chris.whitson@abqshow.com")
      objMM.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "1notoner2")
      objMM.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", 25)
      objMM.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1)
      objMM.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing", 2)
      objMM.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout", 10)
      objMM.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", False)

   End Sub
   Sub MakeActiveAd()
      Dim connectionString As String = ConfigurationManager.ConnectionStrings("DBConnectionString1").ConnectionString
      Dim updateSql As String = "UPDATE ad_listings SET bizFree = @bizFree WHERE adID = " & Custom
      Using myConnection As New SqlConnection(connectionString)
         Dim myCommand As New SqlCommand(updateSql, myConnection)
         myCommand.Parameters.AddWithValue("@bizFree", False)
         myCommand.Parameters.AddWithValue("@adId", Custom)
      End Using
   End Sub
   Sub MakeINActiveAd()
      Dim connectionString As String = ConfigurationManager.ConnectionStrings("DBConnectionString1").ConnectionString
      Dim updateSql As String = "UPDATE ad_listings SET bizFree = @bizFree WHERE adID = " & Custom
      Using myConnection As New SqlConnection(connectionString)
         Dim myCommand As New SqlCommand(updateSql, myConnection)
         myCommand.Parameters.AddWithValue("@bizFree", True)
         myCommand.Parameters.AddWithValue("@adId", Custom)
      End Using
   End Sub
   Sub LogTheError()
      Dim connectionString As String = ConfigurationManager.ConnectionStrings("AspNetSqlProvider").ConnectionString
      Dim insertSql As String = "INSERT INTO pmt_errors_log(adid, response, txn_id, txn_type, receiver_email, payment_status, payment_gross, timestamp) VALUES (@adid, @response, @txn_id, @txn_type, @receiver_email, @payment_status, @payment_gross, @timestamp)"
      Using myConnection As New SqlConnection(connectionString)
         Dim myCommand As New SqlCommand(insertSql, myConnection)
         myCommand.Parameters.AddWithValue("@adid", Custom)
         myCommand.Parameters.AddWithValue("@response", Response)
         myCommand.Parameters.AddWithValue("@txn_id", Txn_id)
         myCommand.Parameters.AddWithValue("@txn_type", Txn_type)
         myCommand.Parameters.AddWithValue("@receiver_email", Receiver_email)
         myCommand.Parameters.AddWithValue("@payment_status", Payment_status)
         myCommand.Parameters.AddWithValue("@payment_gross", Payment_gross)
         myCommand.Parameters.AddWithValue("@timestamp", DateTime.Now)
      End Using
   End Sub
End Class



I used paypal in asp.net application.but there is problem in that when I login for buyer through my website I gives error message "Incorrect email or password" but password and username is correct.Because when I login from paypal website with same login Id and password I can acess the account




 i use paypal service and create text a/c as personal a/c and business a/c in developer.paypal.com

in sandbox

i use this sevice for getting my token no in paypal i set my business id in web confic

but when i am checkout  i don't know which Id and password is used to login in paypal for token no



<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure