Sunday, February 22, 2009

How to Integration PayPal With ASP.NET C#

Hi
I have Integration Paypal Payment System to our website.When i got the job I don't have Any exprence to develope any payment system.I face somany Problem to intregate that systen.
So i am writing this bloge for the new devloper who is willing to Develop Paypel system with ASP.NET C#.
2a. Insert this code snippet into the section of your code that handles shopping cart.*

2b. Create these files to your shopping cart web directory
expresscheckout.aspx


expresscheckout.aspx.cs
using System;
using System.Web;
public partial class PayPalEC : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
NVPAPICaller test = new NVPAPICaller();
string retMsg = "";
string token = "";

if ( Session["payment_amt"] != null)
{
string amt = Session["payment_amt"].ToString();
bool ret = test.ShortcutExpressCheckout(amt, ref token, ref retMsg);
if (ret)
{
Session["token"] = token;
Response.Redirect( retMsg );
}
else
{
Response.Redirect("APIError.aspx?" + retMsg);
}
}
else
{
Response.Redirect( "APIError.aspx?ErrorCode=AmtMissing" );
}
}
}
APIError.aspx.cs


paypalfunctions.cs ( Please save this file into the AppCode sub directory of your .Net web app )

using System;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Text;
using System.Data;
using System.Configuration;
using System.Web;

///
/// Summary description for NVPAPICaller
///

public class NVPAPICaller
{
//private static readonly ILog log = LogManager.GetLogger(typeof(NVPAPICaller));

private string pendpointurl = "https://api-3t.paypal.com/nvp";
private const string CVV2 = "CVV2";

//Flag that determines the PayPal environment (live or sandbox)
private const bool bSandbox = true;

private const string SIGNATURE = "SIGNATURE";
private const string PWD = "PWD";
private const string ACCT = "ACCT";

public string APIUsername = "YourAPIUsername ";
private string APIPassword = "YourAPIPassword ";
private string APISignature = "YourSignature ";
private string Subject = "";
private string BNCode = "PP-ECWizard";

//HttpWebRequest Timeout specified in milliseconds
private const int Timeout = 5000;
private static readonly string[] SECURED_NVPS = new string[] { ACCT, CVV2, SIGNATURE, PWD };


///
/// Sets the API Credentials
///

///
///
///
///
public void SetCredentials(string Userid, string Pwd, string Signature)
{
APIUsername = Userid;
APIPassword = Pwd;
APISignature = Signature;
}

///
/// ShortcutExpressCheckout: The method that calls SetExpressCheckout API
///

///
///
///
///
public bool ShortcutExpressCheckout(string amt, ref string token, ref string retMsg)
{
string host = "www.paypal.com";
if (bSandbox)
{
pendpointurl = "https://api-3t.sandbox.paypal.com/nvp";
host = "www.sandbox.paypal.com";
}

string returnURL = "http://www.yourstore.com/OrderConfirmPage.aspx";
string cancelURL = "http://wwww.yourstore.com/MainPage.aspx";

NVPCodec encoder = new NVPCodec();
encoder["METHOD"] = "SetExpressCheckout";
encoder["RETURNURL"] = returnURL;
encoder["CANCELURL"] = cancelURL;
encoder["AMT"] = amt;
encoder["PAYMENTACTION"] = "Sale";
encoder["CURRENCYCODE"] = "USD";

string pStrrequestforNvp = encoder.Encode();
string pStresponsenvp = HttpCall(pStrrequestforNvp);

NVPCodec decoder = new NVPCodec();
decoder.Decode(pStresponsenvp);

string strAck = decoder["ACK"].ToLower();
if (strAck != null && (strAck == "success" strAck == "successwithwarning"))
{
token = decoder["TOKEN"];

string ECURL = "https://" + host + "/cgi-bin/webscr?cmd=_express-checkout&" + "&token=" + token;

retMsg = ECURL;
return true;
}
else
{
retMsg = "ErrorCode=" + decoder["L_ERRORCODE0"] + "&" +
"Desc=" + decoder["L_SHORTMESSAGE0"] + "&" +
"Desc2=" + decoder["L_LONGMESSAGE0"];

return false;
}
}

///
/// MarkExpressCheckout: The method that calls SetExpressCheckout API, invoked from the
/// Billing Page EC placement
///

///
///
///
///
public bool MarkExpressCheckout(string amt,
string shipToName, string shipToStreet, string shipToStreet2,
string shipToCity, string shipToState, string shipToZip,
string shipToCountryCode,ref string token, ref string retMsg)
{
string host = "www.paypal.com";
if (bSandbox)
{
pendpointurl = "https://api-3t.sandbox.paypal.com/nvp";
host = "www.sandbox.paypal.com";
}

string returnURL = "http://www.yourstore.com/OrderConfirmPage.aspx";
string cancelURL = "http://wwww.yourstore.com/MainPage.aspx";

NVPCodec encoder = new NVPCodec();
encoder["METHOD"] = "SetExpressCheckout";
encoder["RETURNURL"] = returnURL;
encoder["CANCELURL"] = cancelURL;
encoder["AMT"] = amt;
encoder["PAYMENTACTION"] = "Sale";
encoder["CURRENCYCODE"] = "USD";

//Optional Shipping Address entered on the merchant site
encoder["SHIPTONAME"] = shipToName;
encoder["SHIPTOSTREET"] = shipToStreet;
encoder["SHIPTOSTREET2"] = shipToStreet2;
encoder["SHIPTOCITY"] = shipToCity;
encoder["SHIPTOSTATE"] = shipToState;
encoder["SHIPTOZIP"] = shipToZip;
encoder["SHIPTOCOUNTRYCODE"]= shipToCountryCode;


string pStrrequestforNvp = encoder.Encode();
string pStresponsenvp = HttpCall(pStrrequestforNvp);

NVPCodec decoder = new NVPCodec();
decoder.Decode(pStresponsenvp);

string strAck = decoder["ACK"].ToLower();
if (strAck != null && (strAck == "success" strAck == "successwithwarning"))
{
token = decoder["TOKEN"];

string ECURL = "https://" + host + "/cgi-bin/webscr?cmd=_express-checkout&" + "&token=" + token;

retMsg = ECURL;
return true;
}
else
{
retMsg = "ErrorCode=" + decoder["L_ERRORCODE0"] + "&" +
"Desc=" + decoder["L_SHORTMESSAGE0"] + "&" +
"Desc2=" + decoder["L_LONGMESSAGE0"];

return false;
}
}



///
/// GetShippingDetails: The method that calls SetExpressCheckout API, invoked from the
/// Billing Page EC placement
///

///
///
///
public bool GetShippingDetails(string token, ref string PayerId, ref string ShippingAddress, ref string retMsg)
{

if (bSandbox)
{
pendpointurl = "https://api-3t.sandbox.paypal.com/nvp";
}

NVPCodec encoder = new NVPCodec();
encoder["METHOD"] = "GetExpressCheckoutDetails";
encoder["TOKEN"] = token;

string pStrrequestforNvp = encoder.Encode();
string pStresponsenvp = HttpCall( pStrrequestforNvp );

NVPCodec decoder = new NVPCodec();
decoder.Decode( pStresponsenvp );

string strAck = decoder["ACK"].ToLower();
if (strAck != null && (strAck == "success" strAck == "successwithwarning"))
{
ShippingAddress = " ";
ShippingAddress += " ";
ShippingAddress += " ";
ShippingAddress += " ";
ShippingAddress += " ";
ShippingAddress += " ";
ShippingAddress += " ";
ShippingAddress += " ";
ShippingAddress += " ";
ShippingAddress += " ";
ShippingAddress += "";

return true;
}
else
{
retMsg = "ErrorCode=" + decoder["L_ERRORCODE0"] + "&" +
"Desc=" + decoder["L_SHORTMESSAGE0"] + "&" +
"Desc2=" + decoder["L_LONGMESSAGE0"];

return false;
}
}


///
/// ConfirmPayment: The method that calls SetExpressCheckout API, invoked from the
/// Billing Page EC placement
///

///
///
///
public bool ConfirmPayment(string finalPaymentAmount, string token, string PayerId, ref NVPCodec decoder, ref string retMsg )
{
if (bSandbox)
{
pendpointurl = "https://api-3t.sandbox.paypal.com/nvp";
}

NVPCodec encoder = new NVPCodec();
encoder["METHOD"] = "DoExpressCheckoutPayment";
encoder["TOKEN"] = token;
encoder["PAYMENTACTION"] = "Sale";
encoder["PAYERID"] = PayerId;
encoder["AMT"] = finalPaymentAmount;

string pStrrequestforNvp = encoder.Encode();
string pStresponsenvp = HttpCall(pStrrequestforNvp);

decoder = new NVPCodec();
decoder.Decode(pStresponsenvp);

string strAck = decoder["ACK"].ToLower();
if (strAck != null && (strAck == "success" strAck == "successwithwarning"))
{
return true;
}
else
{
retMsg = "ErrorCode=" + decoder["L_ERRORCODE0"] + "&" +
"Desc=" + decoder["L_SHORTMESSAGE0"] + "&" +
"Desc2=" + decoder["L_LONGMESSAGE0"];

return false;
}
}


///
/// HttpCall: The main method that is used for all API calls
///

///
///
public string HttpCall(string NvpRequest) //CallNvpServer
{
string url = pendpointurl;

//To Add the credentials from the profile
string strPost = NvpRequest + "&" + buildCredentialsNVPString();
strPost = strPost + "&BUTTONSOURCE=" + UrlEncode( BNCode );

HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Timeout = Timeout;
objRequest.Method = "POST";
objRequest.ContentLength = strPost.Length;

try
{
using (StreamWriter myWriter = new StreamWriter(objRequest.GetRequestStream()))
{
myWriter.Write(strPost);
}
}
catch (Exception e)
{
/*
if (log.IsFatalEnabled)
{
log.Fatal(e.Message, this);
}*/
}

//Retrieve the Response returned from the NVP API call to PayPal
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
string result;
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
}

//Logging the response of the transaction
/* if (log.IsInfoEnabled)
{
log.Info("Result :" +
" Elapsed Time : " + (DateTime.Now - startDate).Milliseconds + " ms" +
result);
}
*/
return result;
}

///
/// Credentials added to the NVP string
///

///
///
private string buildCredentialsNVPString()
{
NVPCodec codec = new NVPCodec();

if (!IsEmpty(APIUsername))
codec["USER"] = APIUsername;

if (!IsEmpty(APIPassword))
codec[PWD] = APIPassword;

if (!IsEmpty(APISignature))
codec[SIGNATURE] = APISignature;

if (!IsEmpty(Subject))
codec["SUBJECT"] = Subject;

codec["VERSION"] = "2.3";

return codec.Encode();
}

///
/// Returns if a string is empty or null
///

/// the string
/// true if the string is not null and is not empty or just whitespace
public static bool IsEmpty(string s)
{
return s == null s.Trim() == string.Empty;
}
}


public sealed class NVPCodec : NameValueCollection
{
private const string AMPERSAND = "&";
private const string EQUALS = "=";
private static readonly char[] AMPERSAND_CHAR_ARRAY = AMPERSAND.ToCharArray();
private static readonly char[] EQUALS_CHAR_ARRAY = EQUALS.ToCharArray();

///
/// Returns the built NVP string of all name/value pairs in the Hashtable
///

///
public string Encode()
{
StringBuilder sb = new StringBuilder();
bool firstPair = true;
foreach (string kv in AllKeys)
{
string name = UrlEncode(kv);
string value = UrlEncode(this[kv]);
if (!firstPair)
{
sb.Append(AMPERSAND);
}
sb.Append(name).Append(EQUALS).Append(value);
firstPair = false;
}
return sb.ToString();
}

///
/// Decoding the string
///

///
public void Decode(string nvpstring)
{
Clear();
foreach (string nvp in nvpstring.Split(AMPERSAND_CHAR_ARRAY))
{
string[] tokens = nvp.Split(EQUALS_CHAR_ARRAY);
if (tokens.Length >= 2)
{
string name = UrlDecode(tokens[0]);
string value = UrlDecode(tokens[1]);
Add(name, value);
}
}
}

private static string UrlDecode(string s) { return HttpUtility.UrlDecode(s); }
private static string UrlEncode(string s) { return HttpUtility.UrlEncode(s); }

#region Array methods
public void Add(string name, string value, int index)
{
this.Add(GetArrayName(index, name), value);
}

public void Remove(string arrayName, int index)
{
this.Remove(GetArrayName(index, arrayName));
}

///
///
///

public string this[string name, int index]
{
get
{
return this[GetArrayName(index, name)];
}
set
{
this[GetArrayName(index, name)] = value;
}
}

private static string GetArrayName(int index, string name)
{
if (index <>
First Name " + decoder["FIRSTNAME"] + "
Last Name " + decoder["LASTNAME"] + "
Shipping Address
Name " + decoder["SHIPTONAME"] + "
Street1 " + decoder["SHIPTOSTREET"] + "
Street2 " + decoder["SHIPTOSTREET2"] + "
City " + decoder["SHIPTOCITY"] + "
State " + decoder["SHIPTOSTATE"] + "
Zip " + decoder["SHIPTOZIP"] + "


Insert this code snippet into the section of your code that handles billing
if (PaymentOption == "PayPal")
{
NVPAPICaller test = new NVPAPICaller();

string retMsg = "";
string token = "";

if (Session["payment_amt"] != null)
{
string amt = Session["payment_amt"].ToString();

//Optional Shipping Address entered on the merchant site
string shipToName = "";
string shiptToStreet = "";
string shiptToStreet2 = "";
string shipToCity = "";
string shipToState = "";
string shipToZip = "";
string shipToCountryCode = "";

bool ret = test.MarkExpressCheckout(amt, shipToName, shipToStreet, shipToStreet2,
shipToCity, shipToState, shipToZip, shipToCountryCode,
ref token, ref retMsg);
if (ret)
{
Session["token"] = token;
Response.Redirect(retMsg);
}
else
{
Response.Redirect("APIError.aspx?" + retMsg);
}
}
else
{
Response.Redirect( "APIError.aspx?ErrorCode=AmtMissing" );
}
}

To pass the shipping address entered, replaced the shipping address placeholders in the code snippet with variables representing the shipping address from PayPal.

Save the total payment amount in a session variable named "Payment_Amount". The code inside the ExpressCheckout file is designed to read from this session variable and pass as input to the API call.

Order Review - get shipping address from PayPal
Insert this code snippet into the section of your code that handles order review

if (PaymentOption == "PayPal"){ NVPAPICaller test = new NVPAPICaller();
string retMsg = ""; string token = ""; string payerId = "";
token = Session["token"].ToString();
bool ret = test.GetShippingDetails( token, ref payerId, ref shippingAddress, ref retMsg ); if (ret) { Session["payerId"] = payerId; Response.Write ( shippingAddress ); } else { Response.Redirect("APIError.aspx?" + retMsg); }}



Save the total payment amount in a session variable named "Payment_Amount". The code inside the ExpressCheckout file is designed to read from this session variable and pass as input to the API call

Order Confirmation - confirm payment from PayPal
Insert this code snippet into the section of your code that handles order confirmation.
if (PaymentOption == "PayPal"){ NVPAPICaller test = new NVPAPICaller();
string retMsg = ""; string token = ""; string finalPaymentAmount = ""; string payerId = ""; NVPCodec decoder;
token = Session["token"].ToString(); payerId = Session["payerId"].ToString(); finalPaymentAmount = Session["payment_amt"].ToString();
bool ret = test.ConfirmPayment( finalPaymentAmount, token, PayerId, ref decoder, ref retMsg ); if (ret) { // Unique transaction ID of the payment. Note: If the PaymentAction of the request was Authorization or Order, this value is your AuthorizationID for use with the Authorization & Capture APIs. string transactionId = decoder["TRANSACTIONID"];
// The type of transaction Possible values: l cart l express-checkout string transactionType = decoder["TRANSACTIONTYPE"];
// Indicates whether the payment is instant or delayed. Possible values: l none l echeck l instant string paymentType = decoder["PAYMENTTYPE"];
// Time/date stamp of payment string orderTime = decoder["ORDERTIME"];
// The final amount charged, including any shipping and taxes from your Merchant Profile. string amt = decoder["AMT"];
// A three-character currency code for one of the currencies listed in PayPay-Supported Transactional Currencies. Default: USD. string currencyCode = decoder["CURRENCYCODE"]; // PayPal fee amount charged for the transaction string feeAmt = decoder["FEEAMT"];
// Amount deposited in your PayPal account after a currency conversion. string settleAmt = decoder["SETTLEAMT"];
// Tax charged on the transaction. string taxAmt = decoder["TAXAMT"];
//' Exchange rate if a currency conversion occurred. Relevant only if your are billing in their non-primary currency. If string exchangeRate = decoder["EXCHANGERATE"]; } else { Response.Redirect("APIError.aspx?" + retMsg); }}

19 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. i m facing Error in his line--> NVPAPICaller

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. this blog contents are copy and past from the paypal site. if you really wanna help go paypal. it's easy than reading this. ( http://integrationwizard.x.com/ecpaypal/code.php )

    but paypal also giving codes with errors. simply can get those at compile time.. but with your SE knowledge you can fix them.. then you can get errors at run time.. first you get errors with session..( Session["payment_amt"] ) you can see this same variable read with spelling mistakes.. hmm you can proceed with fixing.. but you will have more errors... LOL.

    ReplyDelete
    Replies
    1. give complete information about paypal integration.urgent please my emailid:samyraj1989@gmail.com

      Delete
  5. i m facing problem in this

    strPost = strPost + "&BUTTONSOURCE=" + UrlEncode(BNCode );


    Error is : CS0103: The name 'UrlEncode' does not exist in the current context


    i have also using using.system.web

    still it give Error

    ReplyDelete
  6. Hi,

    This is Asha Bhatt

    if (PaymentOption == "PayPal")

    here what is the "PaymentOption " .It is radiobuttonlist or any other control.

    and where should i write billing code and confirm code

    ReplyDelete
  7. i m facing problem the same problem which kiran has mentioned above can you help me out??? in this

    strPost = strPost + "&BUTTONSOURCE=" + UrlEncode(BNCode );


    Error is : CS0103: The name 'UrlEncode' does not exist in the current context


    i have also using using.system.web

    still it give Error

    ReplyDelete
  8. How do I send cart details please? i.e. so that the shopper can see what they are buying when transferred to PayPal site?

    ReplyDelete
  9. Why not just go the original article at the excellent asp.net site ?? It reveals all - step by step.

    http://www.asp.net/web-forms/tutorials/aspnet-45/getting-started-with-aspnet-45-web-forms/checkout-and-payment-with-paypal

    ReplyDelete
  10. This is awesome!! Really helpful for me and developers. Thanks for sharing with us. Following links also helped me to complete my task.

    http://www.mindstick.com/Articles/41de052a-37e1-41db-aa4c-123313be444a/?How%20to%20integrate%20PayPal%20in%20Asp%20Net

    http://www.codeproject.com/Tips/474197/PayPal-Gateway-Integration-in-ASP-NET

    ReplyDelete
  11. try the following URL

    http://rochcass.wordpress.com/2012/09/04/paypal-direct-payment-for-c-developers/

    ReplyDelete
  12. Hi,Designing websites is like assembling crafts in Web Design Cochin. You just need one or two raw materials, the proper tools, and your old, trusty creative mind. Thanks........

    ReplyDelete
  13. This review was so good and cool, I never imaging I would be able to get a post like this that is so important about Paypal. Really, over some years I have had people complaining about Paypal, thank you once more for the update you are great in developing contents and informaton.
    https://www.tecteem.com/paypal-login/

    ReplyDelete
  14. Look at the latest solution of PayPal checkout in ASP.NET, test the demo on: https://techtolia.com/PayPal/

    Receive payments from PayPal, PayPal Credit, credit or debit cards, Bancontact, BLIK, eps, giropay, iDEAL, MyBank, Przelewy24, SEPA-Lastschrift, Sofort, Venmo via PayPal.

    ReplyDelete
  15. If you are looking the latest solution of PayPal payment integration in ASP.NET & C# (Using Orders v2 REST API with PayPal JavaScript SDK, Server-side Integration), check the demo >>>> https://techtolia.com/PayPal/

    ReplyDelete
  16. Hi, I want to thank you for sharing this interesting information.
    it's great that nowadays we have an opportunity to share our thoughts. it seems to me, blogs and online services are our future. One and good example
    nice post
    please keep sharing more posts like this
    --------------------------
    if you want to contact a techniian for any query or support go to Amazon Belgie

    ReplyDelete