Software Business Partners: .NET and C++ outsourcing company from Romania
 

Simple way to integrate PayPal into your C# web app - Part 2

Sep 22, 2015 by BogdanD

Last time we spoke, we took a look at the general purchase flow via PayPal. Today, we'll look at Point B from our check-list, namely how to actually insert a PayPal button in a C# application, along with the necessary steps for a successful call to the API.

To this end, we'll use the code from a small sample project, containing the bare minimum that is needed to illustrate the process. To keep things simple, the data appended to the NVP string is hardcoded. This string is used to send the required information to the PayPal API, however you'll want to populate the string dynamically - unless your company is selling flat rate services... at which point it's still a bad idea to do this :)

So let's see the code. Try to follow along with the explanation (and post any questions you have in a comment please)

namespace PayPal_Sample_Project
{
public partial class _Default : System.Web.UI.Page
 {
    protected void Page_Load(object sender, EventArgs e)
    {
       if (!Page.IsPostBack && !string.IsNullOrEmpty(Request.QueryString["PayerID"])) // On page load, the application searches for the PayerID.  This will be provided when returning from the PayPal portal along with a transaction token. This token is generated when the call is made and will be sent  regardless if the transaction is completed on PayPal's side or if the purchase was cancelled. It is nothing more than a tracking ID used by PayPal for a specific session.
       {
           lblPayPalSuccess.Visible = true;
           btnPayPalExpressCheckout.Visible = false;
       }
    }

   // Lets see what happens when you click the PayPal button in the page:
   protected void btnPayPalExpressCheckout_Click(object sender, EventArgs e)
   {
       string endpoint = "https://api-3t.sandbox.paypal.com/nvp";
       string redirectUrl = "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token={0}";
       // This are the URLs the PayPal process uses. The endpoint URL is created using the NVP string generated below while the redirect url is where the page the user will navigate to when leaving PayPal plus the PayerID and the token the API returns when the request is made.
            
       string NVP = string.Empty;
 
       // API call method: add the desired checkout method. As I've mentioned above, we're using the express checkout.
       NVP += "METHOD=SetExpressCheckout";  
       NVP += "&VERSION=123";

       // Credentials identifying you as the merchant
       NVP += "&USER=Your_Test_Merchant_Account_User";
       NVP += "&PWD=Your_Test_Account_Password";
       NVP += "&SIGNATURE=Your_Test_Account_Signature";
 
       // Redirect from PayPal portal
       NVP += "&RETURNURL=" + Request.Url.AbsoluteUri;   // Return URL from the PayPal portal for completed payment
       NVP += "&CANCELURL=" + Request.Url.AbsoluteUri;   // Return URL from the PayPal portal for a cancelled purchase
            
       // Payment request information
       NVP += "&PAYMENTREQUEST_0_PAYMENTACTION=Sale";   // Type of transaction
       NVP += "&PAYMENTREQUEST_0_AMT=100";                 // Total payment for the transaction   
       NVP += "&PAYMENTREQUEST_0_ITEMAMT=80";             // Purchased product price
       NVP += "&PAYMENTREQUEST_0_SHIPPINGAMT=10";         // Shipping amount
       NVP += "&PAYMENTREQUEST_0_HANDLINGAMT=5";         // Handling charges
       NVP += "&PAYMENTREQUEST_0_TAXAMT=5";             // Tax amount
 
       // Products involved in the transaction
       NVP += "&L_PAYMENTREQUEST_0_NAME0=Sample Product";                // Product name
       NVP += "&L_PAYMENTREQUEST_0_DESC0=This is a sample product";    // Product description
       NVP += "&L_PAYMENTREQUEST_0_AMT0=80";                            // Product price
       NVP += "&L_PAYMENTREQUEST_0_QTY0=1";                            // Product quantity
            
       // Make the API call to the PayPal Service
       HttpWebRequest request = (HttpWebRequest)WebRequest.Create(endpoint);
       request.Method = "POST";
       request.ContentLength = NVP.Length;
            
       string sResponse = string.Empty;
       using(StreamWriter sw = new StreamWriter(request.GetRequestStream()))
       {
           sw.Write(NVP);
       }

       HttpWebResponse response = (HttpWebResponse)request.GetResponse();
       using (StreamReader sr = new StreamReader(response.GetResponseStream()))
       {
           sResponse = sr.ReadToEnd();
       }
         
       // Receive the token for the operation and redirect the user to the generated URL for the PayPal portal
       string token = string.Empty;
       string[] splitResponse = sResponse.Split('&');
       if (splitResponse.Length> 0)
       {
           foreach (string responseField in splitResponse)
           {
               if (responseField.Contains("TOKEN"))
               {
                   token = responseField.Substring(6);
                   break;
               }
           }
 
           if (!string.IsNullOrEmpty(token))
           {
               redirectUrl = string.Format(redirectUrl, token);
               Response.Redirect(redirectUrl);
           }
       }

       // If we get here, something went wrong;
       lblError.Visible = true;            // Simple error handling :)
   }
 }
} 

Once the above flow is completed, the user will be returned to the specified return URL (having the 2 tokens, that confirm the payment, appended in the query string). With this, you get confirmation that your customer approved a payment to you, via PayPal. Up to this point, no actual money has left the buyer's digital wallet. The only transaction that took place was that the buyer informed PayPal of his intent to pay you, and as a response, the service generated a transaction token to be used by your application (to claim payment once the order is submitted).

Come back next week and I'll show you how to finalize the transaction, once your buyer submits his order - so that you can finally cash in on your hard work!

 

Other posts in this series:

Simple way to integrate PayPal into your C# web app - Part 1
Simple way to integrate PayPal into your C# web app - Part 3


Tags: How To  PayPal 


Comments

No comments yet.

Your Comment:






Blog Home   SBP Home
RSS Feed       Contact








 Blog Archives  |  Terms of Use  |  Privacy Policy
© 2017 SBP Romania. All rights reserved.